【问题标题】:Unable to write into text file using ios:ate in c++无法在 C++ 中使用 ios:ate 写入文本文件
【发布时间】:2023-03-30 19:59:01
【问题描述】:

我正在使用 Visual Studio 2017 练习 C++,我在 TurboC++ 上有过一些 C++ 的经验。 尝试创建一个从文件读取和写入的程序,当我在打开文件时使用“ios::Ate”时遇到问题。

file.open("text.txt", ios::ate);

我的代码如下。

#include "pch.h"
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream file;
    file.open("text.txt", ios::ate);

    char a;

    while(1){
        cin.get(a);
        if (a != '0')
            file << a;
        else break;
    }

    file.close();
}

当我运行这个程序时,它运行没有错误,但是当我打开文件时它是空的。

我尝试使用 ios::out 并且效果很好,但我不想每次写入文件时都截断文件。

【问题讨论】:

标签: c++ file-handling


【解决方案1】:

您的代码假定文件存在。您没有指定 i/o 方向,您应该始终检查是否有操作,例如file.open,成功。

int main()
{
    fstream file;

// open or create file if it doesn't exist, append.
    file.open("text.txt", fstream::out | fstream::app);

// did the file open?
    if (file.is_open()) {
        char a;

        while (1) {
            cin.get(a);
            if (a != '0')
                file << a;
            else break;
        }

        file.close();
    }
}

【讨论】:

  • 我试过了(甚至复制并粘贴了确切的代码),每次执行后我的文件都会被截断。所写的都是最近的条目。
  • 使用 fstream::app 追加,如 NathanOliver 的第一条评论所述。我已经相应地修改了代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
相关资源
最近更新 更多