我正在使用 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/