I am reading a ~2mb CSV file of about 40000 lines and each line defines an object in a list and I need to reflect any changes on the input file to my list and vice-versa... Say if I modify a line on the input file I need to update my object on the list and a modification on the object will be reflected to file immediately. I know it can be done in an infinite while loop but its quite waste of resources and sounds ridiculous. Is there a function or an update flag which I can check or some other approach that I read the file only when updated? I am coding in C++ by the way :)
EDITED
I played a while with the code @Jake proposed and come out with a working solution. Here is a better question for you then... the code I wrote seems working instantly sometimes but sometimes it does not updates the modifications I made to file as I save the file and only after saving file 3 or 5 times more I see the update? What could be the reason for that? Can I improve this solution any further?
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#define INFILE "test.txt"
using namespace std;
__time_t getFileModifyTime(char *filePath)
{
struct stat attrib;
stat(filePath, &attrib);
__time_t date = attrib.st_mtime ;
return date;
}
int main(){
ifstream infile;
infile.open (INFILE);
string currentLine;
__time_t lastUpdateTime = 0;
while(true) // start an infinite loop
{
if(lastUpdateTime != getFileModifyTime(INFILE)) {
cout << "last update time : " << lastUpdateTime << endl;
cout << "modification time : " << getFileModifyTime(INFILE) << endl;
infile.close();
infile.open (INFILE);
while (getline(infile, currentLine)) {
cout << currentLine << endl;
}
}
lastUpdateTime = getFileModifyTime(INFILE);
}
return 0;
}