0

This is my code

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::fstream file;
    file.open("text.txt", std::fstream::in | std::fstream::out | 
              std::fstream::app);
    if(!file.is_open())
    {
        std::cout << "Could not open file(test.txt)" << std::endl;
    } else {
        file << "These are words \nThese words are meant to show up in the new file \n" << 
                "This is a new Line \nWhen the new fstream is created, all of these lines should be read and it should all copy over";

        std::string text;
        file >> text;
        std::cout << text << std::endl;
        file.close();

        std::fstream newFile;
        newFile.open("text2.txt", std::fstream::in | std::fstream::out | 
                     std::fstream::app);

        if(newFile.is_open())
        {
            newFile << text;
        }
    }
}

I'm trying to copy the contents of text.txt to text2.txt but for some reason the text string always ends up empty. I've checked the files and text gets populated but text2 is empty. What's going wrong here?

Student
  • 769
  • 1
  • 6
  • 11
Kenny Castro
  • 114
  • 11

2 Answers2

2

When you append a string to an fstream, the input / output position is set to the end of the file. This means that when you next read from the file, all you will see is an empty string.

You can check what the current input position is by using:

file.tellg()

And set the input / output position to the start by using:

file.seekg(0)

The full reference for std::fstream is here.

Bruce Collie
  • 414
  • 3
  • 6
1

You're trying to read from the end of the file. The position is set to the end of the last thing you wrote to the file, so, if you want to read what you wrote, you have to reset it:

file.seekg(0);

This will set the position for the input back to the start of the file. Note however that reading from the file the way you do now will simply get you 1 word (up to the first whitespace). If you want to read it all, perhaps you should look at something like: Read whole ASCII file into C++ std::string.

Qubit
  • 1,110
  • 6
  • 17