[英]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.