【发布时间】:2021-11-21 20:56:59
【问题描述】:
我正在尝试创建一个线程,当从 main.c 调用时可以读取文件中的行数
main.c
#include <stdio.h>
#define MAX_FILE_NAME 100
#include "t_func.h"
#include <pthread.h>
int main(){
int linecount;
pthread_t thread_id;
FILE *fh = fopen("/home/usr154/out.log", "r");
pthread_create(&thread_id, NULL, count_lines,&fh);
pthread_join(thread_id, (void **) linecount);
printf("lines: %d \n", linecount);
}
t_func.h
#include <stdlib.h>
#include <stdio.h>
int count_lines(int *fh){
char c;
int count =0;
if (fh == NULL)
{
printf("Could not open file %s", fh);
return 0;
}
for (c = getc(fh); c != EOF; c = getc(fh))
if (c == '\n')
count++;
fclose(fh);
return count;
}
我面临 2 个(或更多)问题,文件指针未被接受且返回值未被处理,非常感谢任何帮助(我是 C 编程新手)。
【问题讨论】:
-
在
pthread_create中将&fh更改为fh。还将int *fh更改为void *arg,然后在函数内部添加FILE *fh = arg; -
用
(void **) &linecount致电pthread_join()。 -
printf("Could not open file %s", fh);不会编译,因为 fh 在您的代码中是 int *。如果您希望两者都传递一个结构,或者更好,请在main()或线程中进行打开的同一范围内进行错误检查。 -
另外,隐含地提到,但你混淆了返回 int 的 open 和返回 FILE * 的 fopen。
-
"没有工作'没有帮助。你到底做了什么改变,确切的错误/问题是什么?正如其他 cmets 所指出的那样,你的代码中有很多错误。你修复了吗他们都?