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);
Don’t open the file in append mode if you don’t plan on only appending to it.
From the POSIX reference for
fopen:Looks like you’re looking for
r+mode.