seekg

fstream seekg(), seekp(), and write()

百般思念 提交于 2019-11-28 08:15:32
I'm looking for some clarification on how seekg() and seekp() works with respect to when you are writing to a file. Say for instance I had a file like so: offset 0: 2 offset 4: 4 offset 8: 6 offset 12: 8 offset 16: 10 Now I want to open the file and do some seeks to read and write values. fstream file; file.open("file.txt", fstream::in |fstream::out | fstream::binary); file.seekp(0, ios::end) // seek to the end of the file int eofOffset = file.tellp(); // store the offset of the end-of-file, in this case 20 int key = 0; file.seekg(12, ios::beg); // set the seek cursor to offset 12 from the

How to read a growing text file in C++?

我怕爱的太早我们不能终老 提交于 2019-11-27 01:38:22
I am trying to read from a file which is growing (something similar to what tail -F does), but there must be some problems with my code: string log, logFile("test.log"); size_t p = 0; while(true) { ifstream ifs(logFile.c_str()); ifs.seekg(p); //*1 while(ifs.eof() == false) { getline(ifs, log); cout << log << endl; p = ifs.tellg(); //*2 } nanosleep(&pause, NULL); } Without the lines //*1 and //*2, the log file is correctly read up to its end, but if new lines are added nothing happens. With seekg and tellg I am trying to store the current end position of the file, so that when I reopen it I can

How to read a growing text file in C++?

我与影子孤独终老i 提交于 2019-11-26 22:14:14
问题 I am trying to read from a file which is growing (something similar to what tail -F does), but there must be some problems with my code: string log, logFile("test.log"); size_t p = 0; while(true) { ifstream ifs(logFile.c_str()); ifs.seekg(p); //*1 while(ifs.eof() == false) { getline(ifs, log); cout << log << endl; p = ifs.tellg(); //*2 } nanosleep(&pause, NULL); } Without the lines //*1 and //*2, the log file is correctly read up to its end, but if new lines are added nothing happens. With