1

I am using ifstream to open a file and read line by line and print to console. Now, I also want to make sure that if the file gets updated, it reflects. My code should handle that.

I tried setting fseek to end of the file and then looking for new entries by using peek. However, that did not work.

Here's some code I used

bool ifRead = true;
while (1)
{
    if (ifRead)
    {
        if (!file2read.eof())
        {
            //valid file. not end of file.
            while (getline(file2read, line))
                printf("Line: %s \n", line.c_str());
        }
        else
        {
            file2read.seekg(0, file2read.end);
            ifRead = false;
        }
    }
    else
    {
        //I thought this would check if new content is added. 
        //in which case, "peek" will return a non-EOF value. else it will always be EOF.
        if (file2read.peek() != EOF)
            ifRead = true;

    }
}
}

Any suggestions on what could be wrong or how I could do this.

Student
  • 805
  • 1
  • 8
  • 11
Omi
  • 976
  • 2
  • 20
  • 35
  • Are you checking for modifications since a last *date or time*? You could also: 1) Save the stream position of the last write; 2) Use a checksum, like SHA-1 or MD5 to determine if the file was modified. – Thomas Matthews Jul 24 '18 at 15:52
  • You must search your's OS API for file monitoring functions. And read only when the change event is triggered. Add your OS to tags. – zdf Jul 24 '18 at 15:55
  • 1
    See also: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Thomas Matthews Jul 24 '18 at 15:55
  • Its on Windows. – Omi Jul 24 '18 at 16:02
  • 1
    [This is what you are looking for.](https://stackoverflow.com/questions/931093/how-do-i-make-my-program-watch-for-file-modification-in-c) – zdf Jul 24 '18 at 16:03
  • Thanks for the comments. I am programming on Windows using unmanaged C++. Looks like FindFirstChangeNotification is suggested by most users. However, this gives you changes to any file in that particular directory. From a general search it looks like ReadDirectoryChangesW may be more helpful. Anyways, will try out and keep you posted. – Omi Jul 25 '18 at 11:43

0 Answers0