我正在使用VisualStudio2017练习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();
}当我运行这个程序时,is运行时没有错误,但是当我打开文件时它是空的。
我试过使用ios::out,它运行得很好,但是我不想每次想要写入文件时都截断它。
发布于 2019-03-13 14:38:51
您的代码假设文件存在。您没有指定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();
}
}https://stackoverflow.com/questions/55144181
复制相似问题