C language: fopen Mode Comparison

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.