1. 程式人生 > >fstream讀寫建立可能不存在的檔案

fstream讀寫建立可能不存在的檔案

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();
}