I need to write two programs write.cpp & read.cpp to run simultaneously. One of them write(overwrite) to a file and the other one reads from it.
Basically, there is always only one line in the file.
write.cpp performs the operation successfully but read.cpp doesn't show anything. Using tail -f also shows incorrect result.
write.cpp:
#include <stdio.h> #include <ctime> #include <unistd.h> #include <iostream> #include <fstream> #include <string> using namespace std; int main () { ofstream myfile; int i = 70; char c; while(i <85) { myfile.open ("example.txt"); c = i++; myfile << c << endl; myfile.close(); sleep(1); } return 0; } read.cpp:
#include <iostream> #include <fstream> #include <string> #include <unistd.h> using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { sleep(1); getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; } May I know which part of both programs causes the problem and how may I solve it?
read.cpp doesnt show anything.Does it exit? Does it get as far asmyfile.good(). Does it get past it?openin it may fail.unistd.hdoesn't imply portability in mind.