我的问题是如何根据以下信息使控制台正确显示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.
}

fileA.txt
1
2
3
4
5

fileB.txt(文件最初是空白文本文档)。

fileB.txt(代码运行后)
1
2
3
4
5

最佳答案

ofile将具有一个内部缓冲区,如果不刷新它,并且仅写入少量数据(可能多达64kb),则在调用ofile.close()main()末尾之前,不会将任何数据写入输出文件。

只需将ofile.close()移到file.open("fileB.txt")之前即可。

07-24 09:36