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

来源:互联网 发布:百视通网络电视电话 编辑:程序博客网 时间:2024/05/18 02:04

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 readingios::outOpen file for writingios::ateInitial position: end of fileios::appEvery output is appended at the end of fileios::truncIf the file already existed it is erasedios::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 ofstreamifstream and fstream include a default mode when opening files that varies from one to the other:
classdefault mode to parameterofstreamios::out | ios::truncifstreamios::infstreamios::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();
}

原创粉丝点击