Fopen Mode
Genus |
R |
W |
A |
R + |
W + |
A + |
The file must already exist. |
Y |
N |
N |
Y |
N |
N |
File content will be lost |
N |
Y |
N |
N |
Y |
N |
Allow read from stream (fread) |
Y |
N |
N |
Y |
Y |
Y |
Allow write to stream (fwrite) |
N |
Y |
Y |
Y |
Y |
Y |
Write from the end of the stream |
N |
N |
Y |
N |
N |
Y |
Arbitrary Location (fseek) |
Y |
Y |
Y |
Y |
Y |
N |
When the file to be operated is a binary file, you can add the letter B to the stream pattern to indicate it. B can appear before or after the plus sign, for example, Rb, WB, A + B, AB +
Reference: C Language Reference Manual p284 and p285
R +, W +, A +Several Modes
AlthoughR +, W +Both modes allow read and write operations,W +When opening a file, the file content will be cleared. Therefore, when you need to randomly access and read/write the file content, you cannot use this mode.R +MethodFwriteOnly several bytes after the current stream position of the file are overwritten.
Imagine a scenario: if a file is a small database, each record is a persistent data block. Therefore, for data update operations, you must support random access and modify3The offset can be calculated for a field value of the PEN record.(3-1 )*Set the length of long data)ThenFseekIn the past, directFwrite,If yesW +The file content will be lost. The impact of the operation at this time is unknown.
A +Mode slaveFopenThe schema table is the most powerful mode, but it seems that this mode cannot complete file update, no matter how you use itFseekLocate, the starting position of the file stream is always at the end of the file, that is, it cannot be replacedR +, W +These two modes
Summary: If you want to read and write files, try to useR +Open the file,W +It is really a dangerous way to open, andA +I think it can only be used to append data,The most powerful and secure way isR +
# Include <stdio. h>
File * fp = fopen (filename,"R +");
Assert (FP! = NULL );
//Assert reports an error, while W and a Do Not.