首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在c++中使用ios:ate写入文本文件

无法在c++中使用ios:ate写入文本文件
EN

Stack Overflow用户
提问于 2019-03-13 14:23:37
回答 1查看 378关注 0票数 1

我正在使用VisualStudio2017练习C++,我在TurboC++上有过一些C++的经验。试图创建一个从文件中读写的程序,当我在打开文件时使用"ios::Ate“时遇到了问题。

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

我的代码如下。

代码语言:javascript
复制
#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();
}

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

我试过使用ios::out,它运行得很好,但是我不想每次想要写入文件时都截断它。

EN

回答 1

Stack Overflow用户

发布于 2019-03-13 14:38:51

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

代码语言:javascript
复制
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();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55144181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档