Reputation: 337
I have a text file which already has 40 lines of data . I want to write data just before last two lines in a file. I am newbie to c++. I searched online and found few functions like fseek and seekp, but I am not getting how those those functions to change the lines. Can you please give some pointers for this? Thank you in advance.
Upvotes: 0
Views: 646
Reputation: 1675
You say C++, so I assume you mean that and not C. A FIFO comes to mind for this purpose.
$ cat last_two_lines.c | ./a.out
#include <iostream>
#include <string>
#include <deque>
main ()
{
std::deque<std::string> fifo;
while (!std::cin.eof()) {
std::string buffer;
std::getline(std::cin, buffer);
fifo.push_back(buffer);
if (fifo.size() > 2) {
std::cout << fifo.front() << "\n";
fifo.pop_front();
}
}
std::cout << " // LINE INSERTED" << "\n";
while (fifo.size() > 0) {
std::cout << fifo.front() << "\n";
fifo.pop_front();
}
return 0;
// LINE INSERTED
}
Upvotes: 2
Reputation: 1
std::ifstream
std::vector<std::string>
with an entry for each line in the file (you can use std::getline()
and std::vector<std::string>::push_back()
methods to realize this). std::ifstream
std::vector<std::string>::insert()
std::ofstream
You shouldn't mess around with seek
functions in this case; particularly not, if the replacements size changes dynamically.
Upvotes: 3