10.文件IO

文件指针

每个被使用的文件都在内存中开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件的名字,文件状态及
文件当前的位置等)。这些信息是保存在一个结构体变量中的。该结构体类型是有系统声明的,取名FILE.
例如,VS2008编译环境提供的stdio.h 头文件中有以下的文件类型申明:

struct _iobuf{
    char*_ptr; 
    int _cnt; 
    char *_base; 
    int _flag;
    int _file; 
    int _charbuf; 
    int _bufsiz; 
    char*_tmpfname;
    }; 
typedef struct _iobuf FILE;

不同的C编译器的FILE类型包含的内容不完全相同,但是大同小异。
每当打开一个文件的时候,系统会根据文件的情况自动创建一个FILE结构的变量,并填充其中的信息,使用者不必关
心细节。
一般都是通过一个FILE的指针来维护这个FILE结构的变量,这样使用起来更加方便。

打开文件
FILE *fopen(const char *path, const char *mode);

#include <stdio.h>

description:
The fopen() function opens the file whose name is the string pointed
to by pathname and associates a stream with it.
The argument mode points to a string beginning with one of the
following sequences (possibly followed by additional characters, as
described below):

mode:
r+ Open for reading and writing. The stream is positioned at the
beginning of the file.

w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.

w+ Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream is
positioned at the beginning of the file.

a Open for appending (writing at end of file). The file is
created if it does not exist. The stream is positioned at the
end of the file.

a+ Open for reading and appending (writing at end of file). The
file is created if it does not exist. Output is always
appended to the end of the file. POSIX is silent on what the
initial read position is when using this mode. For glibc, the
initial file position for reading is at the beginning of the
file, but for Android/BSD/MacOS, the initial file position for
reading is at the end of the file.

文件使用方式含义如果指定文件不存在
“r”(只读)为了输入数据,打开一个已经存在的文本文件出错
“w”(只写) 为了输出数据,打开一个文本文件建立一个新的文件a”(追加)向文本文件尾添加数据出错rb”(只读)为了输入数据,打开一个二进制文件出错
“wb”(只写)为了输出数据,打开一个二进制文件建立一个新的文件ab"(追加)向一个二进制文件尾添加数据出错
+”(读写)为了读和写,打开一个文本文件出错
“w+”(读写)为了读和写,建议一个新的文件建立一个新文件
“a+”(读写)打开一个文件,在文件尾进行读写建立一个新的文件Tb+”(读写)为了读和写打开一个二进制文件出错
“wb+”(读写)为了读和写,新建一个新的二进制文件建立一个新的文件
“ab+”(读写)打开一个二进制文件,在文件尾进行读和写建立一个新的文件

关闭文件流
int fclose(FILE *stream);

#include <stdio.h>

remarks:
The fclose function closes stream. _fcloseall closes all open streams except stdin, stdout, stderr (and, in MS-DOS®, _stdaux and _stdprn). It also closes and deletes any temporary files created by tmpfile. In both functions, all buffers associated with the stream are flushed prior to closing. System-allocated buffers are released when the stream is closed. Buffers assigned by the user with setbuf and setvbuf are not automatically released.
Parameters
stream: Pointer to FILE structure
Return Value
fclose returns 0 if the stream is successfully closed. _fcloseall returns the total number of streams closed. Both functions return EOF to indicate an error.


linux:
description:
The fclose() function flushes the stream pointed to by stream
(writing any buffered output data using fflush(3)) and closes the
underlying file descriptor.
return value:
Upon successful completion, 0 is returned. Otherwise, EOF is
returned and errno is set to indicate the error. In either case, any
further access (including another call to fclose()) to the stream
results in undefined behavior.

从stream读取数据
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

#include <stdio.h>

remarks:
The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return–linefeed pairs are replaced with single linefeed characters. The replacement has no effect on the file pointer or the return value. The file-pointer position is indeterminate if an error occurs. The value of a partially read item cannot be determined.
Parameters
buffer: Storage location for data
size: Item size in bytes
count: Maximum number of items to be read
Return Value
fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. Use the feof or ferror function to distinguish a read error from an end-of-file condition. If size or count is 0, fread returns 0 and the buffer contents are unchanged.


linux:
description:
The function fread() reads nmemb items of data, each size bytes long,
from the stream pointed to by stream, storing them at the location
given by ptr.
return value:
On success, fread() and fwrite() return the number of items read or
written. This number equals the number of bytes transferred only
when size is 1. If an error occurs, or the end of the file is
reached, the return value is a short item count (or zero).
fread() does not distinguish between end-of-file and error, and
callers must use feof(3) and ferror(3) to determine which occurred.

int fscanf( FILE *stream, const char *format [, argument ]… );

remarks:
The fscanf function reads data from the current position of stream into the locations given by argument (if any). Each argument must be a pointer to a variable of a type that corresponds to a type specifier in format. format controls the interpretation of the input fields and has the same form and function as the format argument for scanf; see scanf for a description of format. If copying takes place between strings that overlap, the behavior is undefined.
Parameters
format: Format-control string
argument: Optional arguments
Return Value
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf or WEOF for fwscanf.

int fgetc( FILE *stream );

remarks:
Each of these functions reads a single character from the current position of a file; in the case of fgetc and fgetwc, this is the file associated with stream. The function then increments the associated file pointer (if defined) to point to the next character. If the stream is at end of file, the end-of-file indicator for the stream is set. Routine-specific remarks follow.
Parameters
stream: Pointer to FILE structure
Return Value
fgetc and _fgetchar return the character read as an int or return EOF to indicate an error or end of file. fgetwc and _fgetwchar return, as a wint_t, the wide character that corresponds to the character read or return WEOF to indicate an error or end of file. For all four functions, use feof or ferror to distinguish between an error and an end-of-file condition. For fgetc and fgetwc, if a read error occurs, the error indicator for the stream is set.

char *fgets(char *restrict s, int n, FILE *restrict stream);

#include <stdio.h>

remark:
The fgets function reads a string from the input stream argument and stores it in string. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in string is appended with a null character. The newline character, if read, is included in the string.
fgets is similar to the gets function; however, gets replaces the newline character with NULL. fgetws is a wide-character version of fgets.
Parameters
string: Storage location for data
n: Maximum number of characters to read
Return Value
Each of these functions returns string. NULL is returned to indicate an error or an end-of-file condition. Use feof or ferror to determine whether an error occurred.


linux:
The functionality described on this reference page is aligned with
the ISO C standard. Any conflict between the requirements described
here and the ISO C standard is unintentional. This volume of
POSIX.1‐2008 defers to the ISO C standard.
The fgets() function shall read bytes from stream into the array
pointed to by s, until n−1 bytes are read, or a is read and
transferred to s, or an end-of-file condition is encountered. The
string is then terminated with a null byte.
The fgets() function may mark the last data access timestamp of the
file associated with stream for update. The last data access
timestamp shall be marked for update by the first successful
execution of fgetc(), fgets(), fread(), fscanf(), getc(), getchar(),
getdelim(), getline(), gets(), or scanf() using stream that returns
data not supplied by a prior call to ungetc().
return value:
Upon successful completion, fgets() shall return s. If the stream is
at end-of-file, the end-of-file indicator for the stream shall be set
and fgets() shall return a null pointer. If a read error occurs, the
error indicator for the stream shall be set, fgets() shall return a
null pointer, and shall set errno to indicate the error.

向stream写入数据
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

#include <stdio.h>

remarks:
The fwrite function writes up to count items, of size length each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written. If stream is opened in text mode, each carriage return is replaced with a carriage-return – linefeed pair. The replacement has no effect on the return value.
Parameters
buffer: Pointer to data to be written
size: Item size in bytes
count: Maximum number of items to be written
Return Value
fwrite returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined.


linux:
description:
The function fwrite() writes nmemb items of data, each size bytes
long, to the stream pointed to by stream, obtaining them from the
location given by ptr.
return value:
On success, fread() and fwrite() return the number of items read or
written. This number equals the number of bytes transferred only
when size is 1. If an error occurs, or the end of the file is
reached, the return value is a short item count (or zero).

int fprintf( FILE *stream, const char *format [, argument ]…);

#include <stdio.h>

remarks:
fprintf formats and prints a series of characters and values to the output stream. Each function argument (if any) is converted and output according to the corresponding format specification in format. For fprintf, the format argument has the same syntax and use that it has in printf.
Parameters
format: Format-control string
argument: Optional arguments
Return Value
fprintf returns the number of bytes written. fwprintf returns the number of wide characters written. Each of these functions returns a negative value instead when an output error occurs.


linux:
description:
fprintf() and vfprintf() write output to the given
output stream;
the functions fprintf() respectively, except
that they are called with a va_list instead of a variable number of arguments.
These functions do not call the va_end macro. Because they invoke the va_arg
macro, the value of ap is undefined after the call.
return value:
Upon successful return, these functions return the number of characters printed
(excluding the null byte used to end output to strings).

int fputc( int c, FILE *stream );

remarks:
Each of these functions writes the single character c to a file at the position indicated by the associated file position indicator (if defined) and advances the indicator as appropriate. In the case of fputc and fputwc, the file is associated with stream. If the file cannot support positioning requests or was opened in append mode, the character is appended to the end of the stream. Routine-specific remarks follow.
Parameters
c: Character to be written
Return Value
Each of these functions returns the character written. For fputc and _fputchar, a return value of EOF indicates an error. For fputwc and _fputwchar, a return value of WEOF indicates an error.


linux:
description:
Each of these functions writes the single character c to a file at the position indicated by the associated file position indicator (if defined) and advances the indicator as appropriate. In the case of fputc and fputwc, the file is associated with stream. If the file cannot support positioning requests or was opened in append mode, the character is appended to the end of the stream. Routine-specific remarks follow.
Parameters
c: Character to be written
return value:
Each of these functions returns the character written. For fputc and _fputchar, a return value of EOF indicates an error. For fputwc and _fputwchar, a return value of WEOF indicates an error.

int fputs( const char *string, FILE *stream );

remarks:
Each of these functions copies string to the output stream at the current position. fputws copies the wide-character argument string to stream as a multibyte-character string or a wide-character string according to whether stream is opened in text mode or binary mode, respectively. Neither function copies the terminating null character.
Parameters
string: Output string
Return Value
Each of these functions returns a nonnegative value if it is successful. On an error, fputs returns EOF, and fputws returns WEOF

设置流指针位置
int fseek(FILE *stream, long offset, int whence);

#include <stdio.h>

remarks:
The fseek function moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin. The next operation on the stream takes place at the new location. On a stream open for update, the next operation can be either a read or a write. The argument origin must be one of the following constants, defined in STDIO.H:
Parameters
offset: Number of bytes from origin
origin: Initial position
Return Value
If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined.


linux:
description:
The fseek() function sets the file position indicator for the stream
pointed to by stream. The new position, measured in bytes, is
obtained by adding offset bytes to the position specified by whence.
If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is
relative to the start of the file, the current position indicator, or
end-of-file, respectively. A successful call to the fseek() function
clears the end-of-file indicator for the stream and undoes any
effects of the ungetc(3) function on the same stream.
return value:
successful completion,
fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the
current offset. Otherwise, -1 is returned and errno is set to
indicate the error.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值