2013-02-11 51 views
2

我想要產生多個線程,併爲每個線程寫入不同的文件(線程1寫入文件1等)。但是,線程執行ferror()之後,阻止我在主進程中執行進一步的文件操作。我試着清除錯誤,但沒有解決。這是我目前擁有的代碼:從多個線程寫入不同文件後獲取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; 

注意,由線程打開的文件不應該存在,如果存在,應該被清除。 任何幫助將不勝感激。謝謝!

回答

2

mode論據fopen應該是"r+"(如果應該存在於文件)或"w+"(或者甚至"a+"),而不是"rw"。不是有效模式的字符串"rw"可能被解釋爲"r"模式,而您不能將fprintf解釋爲這樣的FILE*

+0

真棒「W +」完美工作!謝謝! – pretobomba 2013-02-11 22:15:27