我在作业中遇到了一个我解决不了的问题,你能帮我吗?我在Opensuse Leap 15.4中通过终端进行编译。正如我在标题中提到的,与我们的主程序相同的目录中将有10-20个文本文件,并且这个文本文件将由1和0组成。作为一个程序参数,文本文件名将从终端给出,我将打开这个文本文件,并在其中找到数字1。可以将多个文本文件作为终端程序的参数。我将运行一个线程来读取每个文本文件的内容。
我写了一个代码,它编译没有错误。然而,我得到了"分割错误(核心哑)"&;错误,当我从终端参数化程序。即使文件在同一个目录中,我也根本无法读取它们。这里我将分享我的源代码,哪些部分需要修改,您有什么建议?的例子:
./main 1-10.txt 3-10.txt
Total Number of Ones in All Files: 11
./main 8-10.txt 5-10.txt 4-10.txt
Total Number of Ones in All Files: 14
./main
Total Number of Ones in All Files: 0
./main 1-10M.txt 2-10M.txt 4-10M.txt
Total Number of Ones in All Files: 15001073
--> I will run 3 Threads for 3 text files here to read
./main 8-10.txt xyzqw.txt
Total Number of Ones in All Files: 3
--> It will not read the content of the xyzq.txt file that is not in the directory and will not give an error.
./main *-10M.txt
Total Number of Ones in All Files: 24647735
-->> A program that can work in harmony with wildcards characters
代码:#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int global = 0;
void* func(void *argp) {
char buffer[500];
char *c = argp;
sprintf(buffer, "%s", c);
FILE *fp = fopen(buffer, "r");
char ch;
if (fp == NULL) {
printf("No text file , Number of 1 : 0");
}
do {
ch = fgetc(fp);
if ((int) ch == 1)
global++;
} while (ch != EOF);
}
int main(int argc, char *argv[]) {
int ar = argc - 1;
pthread_t thread[ar];
if (argc >= 2) {
for (int i = 1; i <= ar; i++) {
pthread_create(&thread[i], NULL, func, (void*) argv[i]);
}
for (int i = 1; i <= ar; i++) {
pthread_join(thread[i], NULL);
}
} else {
printf("Filename not entered, Number of 1 -> 0 ");
}
printf("Number of Ones All files %d", global);
}
你想
pthread_create(&thread[i - 1], NULL, func, (void*) argv[i]);
不是
pthread_create(&thread[i], NULL, func, (void*) argv[i]);
,否则在最后一次迭代中访问数组的边界之外。
为了使它更简单,你可以修改main
参数:
if (argc > 1)
{
argc -= 1;
argv += 1;
pthread_t thread[argc];
for (int i = 0; i < argc; i++) {
pthread_create(&thread[i], NULL, func, argv[i]); // you don't need the cast
}
for (int i = 0; i < argc; i++) {
pthread_join(thread[i], NULL);
}