c++ - 无法使用 ios :ate in c++ 写入文本文件

标签 c++ file-handling

我正在使用 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,它工作正常,但我不想每次写入文件时都截断该文件。

最佳答案

您的代码假定该文件存在。你没有指定一个输入/输出方向,你应该总是检查一个操作,例如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();
    }
}

关于c++ - 无法使用 ios :ate in c++ 写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144181/

相关文章:

Java:如何使两个记录器写入不同的文件(Logger)

c# - 如何通过特定的行分隔符读取文本文件?

java - 比较两个 Unicode 文件并将输出写入第三个文件

c++ - 是否可以将某些数据锁定在 CPU 缓存中?

c++ - 为什么 C++ 更喜欢这个模板方法而不是方法重载?

c++ - 解释这个 C++ 函数如何返回一个数组

python - 读取所有目录下的所有文件

c++ - 标准 vector 之上的 C++11 包装器类

c++ - 为什么只打印一个阿姆斯特朗号码?

perl - 使用 Perl 删除一个非常大的文件夹的最佳策略是什么?