我正在尝试生成多个线程,并为每个线程写入不同的文件(线程 1 写入文件 1,等等......)。但是,在线程执行 ferror() 设置后,阻止我在主进程中进行进一步的文件操作。我尝试清除错误,但没有解决。这是我目前拥有的代码:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void * bla (void *arg) {
fprintf((FILE *) arg, "Hey, printing to file");
}
int main() {
FILE *f1 = fopen("out0", "rw");
FILE *f2 = fopen("out1", "rw");
pthread_t t[2];
pthread_create(&t[0], NULL, bla, f1);
pthread_create(&t[1], NULL, bla, f2);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
printf("%d\n", ferror(f2)); // ERROR: ferror() is set to 1 here!
//fseek(f1, 0, SEEK_END);
fseek(f2, 0, SEEK_END);
long pos = ftell(f2); // This still works
printf("%ld\n", pos);
clearerr(f2); // Trying to clear the error, flag clears, but further operations fail
char *bytes = malloc(pos);
int err = fread(bytes, 1, 4, f2); // fread returns 0
printf("%d\n", ferror(f2));
printf("%d\n", err);
bytes[pos-1] = '\0';
printf("%s", bytes);
free (bytes);
fclose(f1);
fclose(f2);
return 0;
注意线程打开的文件不应该存在,如果存在就应该清除。任何帮助将不胜感激。谢谢!