【发布时间】:2020-01-10 17:59:53
【问题描述】:
我的问题是如何让我的控制台根据以下信息正确显示 fileB 的内容。
以下是我为基本文件输入/输出操作创建的代码。我正在尝试将内容从 fileA 复制到 fileB。完成此操作后,我尝试将 fileB 的内容显示到cout。代码运行并将 fileB 的内容更新为存储在 fileA 中的任何内容。但是,控制台不会显示 fileB 的新内容。它只是显示一个空白框。
#include <iostream> // Read from files
#include <fstream> // Read/Write to files
#include <string>
#include <iomanip>
void perror();
int main()
{
using std::cout;
using std::ios;
using std::ifstream;
ifstream ifile; // ifile = input file
ifile.open("fileA.txt", ios::in);
using std::ofstream;
ofstream ofile("fileB.txt", ios::out); // ios::app adds new content to the end of a file instead of overwriting existing data.; // ofile = output file
using std::fstream;
fstream file; // file open fore read/write operations.
if (!ifile.is_open()) //Checks to see if file stream did not opwn successfully.
{
cout << "File not found."; //File not found. Print out a error message.
}
else
{
ofile << ifile.rdbuf(); //This is where the magic happens. Writes content of ifile to ofile.
}
using std::string;
string word; //Creating a string to display contents of files.
// Open a file for read/write operations
file.open("fileB.txt");
// Viewing content of file in console. This is mainly for testing purposes.
while (file >> word)
{
cout << word << " ";
}
ifile.close();
ofile.close();
file.close();
getchar();
return 0; //Nothing can be after return 0 in int main. Anything afterwards will not be run.
}
文件A.txt
1
2
3
4
5
fileB.txt(文件最初是一个空白文本文档)。
fileB.txt(代码运行后)
1
2
3
4
5
【问题讨论】: