Aparna Savant
Aparna Savant

Reputation: 337

write data at desired line in already existing file

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

Answers (2)

codnodder
codnodder

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

  1. Open your file using a std::ifstream
  2. Read the whole file into a 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).
  3. Close the std::ifstream
  4. Change the vector entry at the line index you want to change, or alternatively insert additional entries to the vector using std::vector<std::string>::insert()
  5. Open your file using a std::ofstream
  6. Write the vectors content back to the file (just iterate over the vector and output each entry to the file).

You shouldn't mess around with seek functions in this case; particularly not, if the replacements size changes dynamically.

Upvotes: 3

Related Questions