I am trying to spawn several threads and for each thread I write to a different file (thread 1 writes to file 1, etc…). However, after the threads execute ferror() is set, preventing me from doing further file operations in the main process. I tried clearing the error, but it did not solve. This is the code I currently have:
#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;
Note that the file opened by the threads should not exist, and if it exists it should be cleared.
Any help would be greatly appreciated. Thanks!
modeargument forfopenshould be"r+"(if the files should exist) or"w+"(or maybe even"a+") instead of"rw". The string"rw", which is not a valid mode, is probably interpreted as"r"mode, and you can’tfprintfto such aFILE*.