【问题标题】:C++ File Input/Output Console OutputC++ 文件输入/输出控制台输出
【发布时间】: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

【问题讨论】:

    标签: c++ file console


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!那成功了。感谢您的解释。它确实帮助我理解了代码中实际发生的事情。
    【解决方案2】:

    这是因为您在打开 FileB 之前没有关闭 oFile 对象。

    ofile.close();
    file.open("fileB.txt");
    
    

    通过这样做,您将可以访问更新的文件。

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多