关闭

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

3904人阅读 评论(0) 收藏 举报
分类:

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::in Open file for reading
ios::out Open file for writing
ios::ate Initial position: end of file
ios::app Every output is appended at the end of file
ios::trunc If the file already existed it is erased
ios::binary Binary 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:
class default mode to parameter
ofstream ios::out | ios::trunc
ifstream ios::in
fstream ios::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();
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:175587次
    • 积分:2753
    • 等级:
    • 排名:第13483名
    • 原创:104篇
    • 转载:11篇
    • 译文:13篇
    • 评论:7条