我试图生成多个线程,并为每个线程写入不同的文件(线程 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;
注意,线程打开的文件不应该存在,如果存在则应清除。 任何帮助将不胜感激。谢谢!
最佳答案
fopen
的
mode
参数应为 "r+"
(如果文件应该存在)或 "w+"
(或者甚至可能是"a+"
)而不是"rw"
。字符串 "rw"
不是有效模式,可能会被解释为 "r"
模式,并且您不能 fprintf
来这样一个FILE*
。
关于c - 从多个线程写入不同文件后获取ferror(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14821552/