C++ 无法使用c+;中的追加模式在文件中插入数据+;
我的代码是:C++ 无法使用c+;中的追加模式在文件中插入数据+;,c++,file,C++,File,我的代码是: #include<iostream> #include<fstream> using namespace std; int main() { fstream file; file.open("abc.txt",ios::app); file<<"hello"; file.close(); return 0; } #包括 #包括 使用名称空间std; int main() { 流文件; 打开(“abc.txt”,ios::app); 文件打开文
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("abc.txt",ios::app);
file<<"hello";
file.close();
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
流文件;
打开(“abc.txt”,ios::app);
文件打开文件时,除了指定append(ios::app
)外,还必须指定要输出到文件(ios::out
)。可以将它们与按位or(|
)组合,因为它们表示单位标志
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("abc.txt",ios::app | ios::out);
file << "hello";
file.close();
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
流文件;
打开(“abc.txt”,ios::app | ios::out);
文件我认为您需要在open()
调用中声明您的文件用于输出和附加(ios::out | ios::app
)但当您不确定文件是否存在时,就是这种情况。如果它不存在,那么它将创建一个。在这里,如果文件abc.txt存在,那么为什么我不能以附加模式直接打开它并向其写入数据?当打开文件流时,需要您声明您是否打算对其进行读取、写入或两者兼而有之。ios:app|ios::out
仍然是追加模式,因为ios::out
仅指定要写入文件。ios::out
将创建一个新文件(如果不存在),或使用现有文件(如果存在)。