Search code examples
c++c++11fstream

C++ Clearing content of text file between runs causes only last line to be written


I am trying to write a few lines into a text file. I would like to empty the file before appending to it, on each run. I am able to clear the previous content, but when I do so, for some reason only the last line of my input file is appended to the output file. I also tried using remove() to erase the file and received the same output.

On the other hand without clearing the file or removing it, everything is appended properly to the output file.

I would be happy to find a way to solve this and perhaps understand why this occurs. I am using C++11.

I looked here: How to clear a file in append mode in C++

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>

int main() {
  std::fstream infile;
  std::string line;

  infile.open("file.txt" , std::ios::in);

  while (std::getline(infile, line)) {
    std::istringstream line_buffer(line);
    std::string word;

    std::fstream outfile;
    outfile.open("out.txt", std::ios::out);
    outfile.close();
    outfile.open("out.txt", std::ios::app);
    while (line_buffer >> word) {
      std::cout << word << " ";
      outfile << word << " ";
    }
    std::cout << std::endl;
    outfile << std::endl;
  }
  return 0;
}

Solution

  • The problem is that you are clearing the file at each iteration of the while loop, you can just open the outfile before the loop like this:

    #include <string>
    #include <fstream>
    #include <sstream>
    #include <iostream>
    #include <stdio.h>
    
    int main() {
      std::fstream infile;
      std::string line;
    
      infile.open("file.txt" , std::ios::in);
    
      std::fstream outfile;
      outfile.open("out.txt", std::ios::out);
    
      while (std::getline(infile, line)) {
        std::istringstream line_buffer(line);
        std::string word;
    
        while (line_buffer >> word) {
          std::cout << word << " ";
          outfile << word << " ";
        }
        std::cout << std::endl;
        outfile << std::endl;
      }
    
      outfile.close();
      return 0;
    }