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

Error copying text from one file to another c++ fstream

本文关键字:另一个 复制 c++ 出错 文件 一个 文本      更新时间:2023-10-16

这是我的代码

#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;
}
}
}

我试图将text.txt的内容复制到text2.txt,但由于某种原因,文本字符串总是以空结尾。我已经检查了文件并填充了文本,但text2为空。这里出了什么问题?

将字符串附加到fstream时,输入/输出位置设置为文件的末尾。这意味着,当您下次读取该文件时,您将看到的只是一个空字符串。

您可以使用检查当前输入位置

file.tellg()

并使用将输入/输出位置设置为起始位置

file.seekg(0)

std::fstream的完整参考资料如下。

您正在尝试从文件的末尾读取。位置设置为您写入文件的最后一个内容的末尾,因此,如果您想读取您写入的内容,则必须重置它:

file.seekg(0);

这将把输入的位置设置回文件的开头。但是,请注意,以现在的方式读取文件只需获得1个单词(最多为第一个空格(。如果您想读取所有内容,也许您应该查看以下内容:将整个ASCII文件读取到C++std::string中。