File Read & Write
C: FILE freopen()
¶
head file: `
File Access Mode String¶
From CPPReference
File access mode string | Meaning | Explanation | Action if file already exists | Action if file does not exist |
---|---|---|---|---|
"r" | read | Open a file for reading | read from start | return NULL and set error |
"w" | write | Create a file for writing | destroy contents | create new |
"a" | append | Append to a file | write to end | create new |
"r+" | read extended | Open a file for read/write | read from start | return NULL and set error |
"w+" | write extended | Create a file for read/write | destroy contents | create new |
"a+" | append extended | Open a file for read/write | write to end | create new |
Note
std::freopen is the only way to change the narrow/wide orientation of a stream once it has been established by an I/O operation or by std::fwide.
Example
Warning
If you have used the untie operation, you shouldn't use freopen because you would have already disabled <cstdio>
.
Tip
If you are using an Online Judge, you can add this macro definition to your code:
Most OJ will use this macro definition, while your computer won't have one, thus you can add freopen in ONLINE_JUDGE so that you can use freopen as it'll be disabled on your OJ.
C++: fstream fiostream
¶
headfile: <fiostream>
¶
function open()
¶
Parameters
ios::app: //open the file as append
ios::ate: //Locate the file to the end of the file when it is opened. ios:app includes this property.
ios::binary: //Open the file as binary, the default is text. See the previous section for the difference between the two methods
ios::in: // the file is opened as input (file data is entered into memory)
ios::out: //files are opened as output (memory data is output to the file)
ios::nocreate: //doesn't create the file, so it fails to open if the file doesn't exist
ios::noreplace: // doesn't overwrite the file, so opening the file fails if the file exists
ios::trunc: // set file length to 0 if file exists
Tip
You can use "or" or "+" to connect the above attributes, such as 3 or 1 | 2 is to open the file with read-only and implicit attributes.