1. 程式人生 > >c讀寫文件

c讀寫文件

inpu r+ class rac repo clas ptr out from

整理一波c讀寫文件的API。

fopen

FILE * fopen ( const char * filename, const char * mode );

打開模式有以下幾種:

"r" read: Open file for input operations. The file must exist.
"w" write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"a" append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
"r+" read/update: Open a file for update (both for input and output). The file must exist.
"w+" write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
"a+" append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

In order to open a file as a binary file, a "b"character has to be included in the mode string.

fread

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.

fwrite

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream.

c讀寫文件