How to force fseek() to move the cursor

I have a program which creates multiple threads and each one of them tries to write 100 bytes in a file at a different location(offset). The first thread writes 100 bytes starting from 0, the second 100 bytes starting from 100, the third 100 bytes starting from 300 and so on If the threads are executed in this order everithing is ok and I do not need fseek. But for real time concurrency if I put the first thread to "sleep(2)" for 2 seconds, wait until all other threads are done, and use fseek to move the file cursor to the begining of the file this doesn't happen. I used mutexes to handle concurrency. Code sample:

    offset=0;//for the first thread
    char data[100];
    int length; // how many chars are currently in data
    FILE * f;

    pthread_mutex_lock(&mutexFileWrite);
    f = fopen(fileName, "a");
    fseek(f,offset, SEEK_SET);  
    fwrite(data,sizeof(char),length,f);
    fclose(f);
    pthread_mutex_unlock(&mutexFileWrite);

Upvotes: 1

Views: 484

Answers (1)

Mat
Mat

Reputation: 206689

Don't open the file in append mode if you don't plan on only appending to it.

From the POSIX reference for fopen:

Opening a file with append mode (a as the first character in the mode argument) shall cause all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek().

Looks like you're looking for r+ mode.

Upvotes: 4

Related Questions