fstream读写创建可能不存在的文件

这篇博客探讨了如何使用C++的fstream库来处理文件。通过fstream::out|fstream::app组合可以创建并追加到文件,而fstream::in|fstream::out则不具有创建文件的属性。示例代码展示了不同打开模式对文件操作的影响,如只写、读写以及追加等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

fstream file("b.txt", fstream::in|fstream::out|fstream::app); 


ate 并不会导致create属性,

app可造成out属性

in 表示只读属性

out表可写属性+create shuxing

in+out 表只读+可写属性(没有创建属性)


dd.out.txt:

s

{
    cout<<"---------------------------------------\n";
fstream file("dd.out.txt", fstream::out); // make dd.out.txt empty
//fstream file("dd.out.txt", fstream::out|fstream::in);
string s;
file>>s;
cout<<s;
file.close();
}




You're specifying std::fstream::in in your call to fstream::open(). This is known to force it to require an existing file.

If you look at e.g. this reference, you will see:

app     seek to the end of stream before each write 

and

ate     seek to the end of stream immediately after open 

This means that ios::app only writes at the end, but that ios::ate reads and writes at the end by default. However, with ios::ate you can seek freely in the file, but with ios::app you will alwayswrite at the end, no matter what position you set for the writing pointer.

void open (const char * filename, openmode mode);
where  filename  is a string of characters representing the name of the file to be opened and  mode  is a combination of the following flags:
ios::inOpen file for reading
ios::outOpen file for writing
ios::ateInitial position: end of file
ios::appEvery output is appended at the end of file
ios::truncIf the file already existed it is erased
ios::binaryBinary mode
These flags can be combined using bitwise operator OR:  | . For example, if we want to open the file "example.bin" in binary mode to add data we could do it by the following call to function-member  open :
ofstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
All of the member functions  open  of classes  ofstream ifstream  and  fstream  include a default mode when opening files that varies from one to the other:
classdefault mode to parameter
ofstreamios::out | ios::trunc
ifstreamios::in
fstreamios::in | ios::out


//fstream file("b1.txt", fstream::in|fstream::out); do NOT create if no exist
fstream file("b1.txt", fstream::out);   // create
file<<"s";
cout<<"s";
file.close();
}


{
fstream file("b.txt", fstream::in|fstream::out|fstream::app); // create
file<<"s";
cout<<"s";
file.close();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值