tags:

views:

52

answers:

1

I'm attempting to exit a while loop, based on file contents. File exists and is empty, or garbage filled at initialization of the program. I externally modify the file, and would like the loop to exit upon this happening based on how the file was modified.

Currently, I start a few threads, open the file that I'm reading from. Check the first byte. If it is a one, I exit, else start the loop.

When I'd like to exit. I put a one in the first byte, but it appears my file is never read again.

While loop statement and variable definition each loop looks like:

 while(strcmp(fileContents, "1\n") != 0){

    lengthRead = fread(fileContents, 1, size, isRecording);
    fseek(isRecording, 0, SEEK_SET);

I know there are probably simpler ways to exit a while loop externally, but based on the architecture of my project, the only way I can see how to control this is to exit based on file contents.

+1  A: 

If your other thread is writing to the file using fwrite() don't forget to call fflush() to actually write the changes out to the file (otherwise, they can remain buffered in memory).

As Dave Jarvis mentioned, there are many other alternatives for synchronizing with another thread. For example, if you're using pthreads, pthread_cond_signal and pthread_cond_wait.

David Gelhar
It's not the simplest system to explain, but the file is being modified by an external program. Basically just a simple python script. While debugging it appears that C never sees the change made in the file. I'm wondering if I'll need to open, read, and then close the file before redefining "fileContents" with fread(). Dave Jarvis idea of checking the existence of a file is a great idea though and I'll be seeing if that is a possible solution.
pri0ritize
David Gelhar
@David: +1. Agreed: don't forget to `fflush()`.
Dave Jarvis