File locking for read and write

Hi all,

I have two threads, one reads a file and one writes to the same file.
I want to lock the file while writing so read is blocked until the file is unlocked.

I tried using flockfile amd funlockfile without success.

Can someone please show the correct way to achieve this.


thread 1:
1
2
3
4
5
6
7
8
9
10
11
FILE * F;
string outFile = "myfile";
string out2File = "string to be stored";

F = fopen(outFile.c_str(), "a");

flockfile(F);
fputs(out2File.c_str(), F);
funlockfile(F);

fclose(FileStream);


thread 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FILE * F2;
unsigned long length;
char * FileContent;
size_t result;
string retContent = "";

string inFile = "myfile";

F2 = fopen(inFile.c_str(), "r");
fseek (F2 , 0 , SEEK_END);
length = ftell (F2);
rewind (F2);

FileContent = (char*) malloc (sizeof(char)*length);
result = fread (FileContent, 1, length, F2);
//.
//.
free (FileContent);
fclose(FileStream);
In my experience, fopen fails if the file has been opened with write permissions (presumably for this very reason). Although in append mode it might be different (I never use append).

Anyway -- "blocking" and "mutually exclusive access to a file" sounds an awful lot like you want a Mutex. Make a mutex and lock it during critical sections (file accesses). Mutexes are fundamental for multithreading and any threading lib should have them.
Topic archived. No new replies allowed.