简体   繁体   English

将文本从一个文件复制到另一c ++ fstream时出错

[英]Error copying text from one file to another c++ fstream

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. 我正在尝试将text.txt的内容复制到text2.txt但是由于某种原因,文本字符串始终以空结尾。 I've checked the files and text gets populated but text2 is empty. 我检查了文件并填充了文本,但text2为空。 What's going wrong here? 这是怎么了

When you append a string to an fstream , the input / output position is set to the end of the file. 将字符串追加到fstream ,输入/输出位置设置为文件的末尾。 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 . std::fstream的完整参考资料在这里

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). 但是请注意,以这种方式从文件中读取将仅使您得到1个单词(直到第一个空格)。 If you want to read it all, perhaps you should look at something like: Read whole ASCII file into C++ std::string . 如果您想全部阅读,也许您应该看一下:将整个ASCII文件读入C ++ std :: string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM