複数のスレッドを生成しようとしていますが、スレッドごとに異なるファイルに書き込みます(スレッド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;
スレッドによって開かれたファイルは存在してはならず、存在する場合はクリアする必要があることに注意してください。どんな助けでも大歓迎です。ありがとう!