[英]Error copying text from one file to another c++ fstream
这是我的代码
#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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.