访问文件
Programs may process no files, one file or several files. Each file used in a program must have a unique name and will have a different file pointer returned by fopen. All subsequent file processing functions after the file is opened must refer to the file with the appropriate file pointer. Files may be opened in one of several modes.
程序可以不处理任何文件,也可以处理一个文件或多个文件。程序中使用的每个文件都必须具有唯一的名称,并且将具有由 fopen 返回的不同文件指针。文件打开后的所有后续文件处理函数都必须使用适当的文件指针引用该文件。文件可以以多种模式之一打开。
FILE ∗ fopen ( const char ∗ filename , const char ∗ mode ) ; {\textit{FILE}}^{*}\ {\textbf{fopen}}{\left( {\textit{const char}}^{*}\ {\text{filename}},\ {\textit{const char}}^{*}\ {\text{mode}} \right)}; FILE∗ fopen(const char∗ filename, const char∗ mode);
如果文件被成功打开,函数 fopen 返回一个指向 FILE
类型对象的指针。否则,返回一个空指针 NULL
,errno
变量也会在失败时设置为系统特定的错误代码。
The program closes the file with fclose and terminates. Function fclose also receives the file pointer as an argument. If function fclose is not called explicitly the operating system normally will close the file when program execution terminates.
程序使用 fclose 关闭文件并终止。函数 fclose 还接收文件指针作为参数。如果函数 fclose 没有显式调用,操作系统通常会在程序执行终止时关闭文件。
int fclose ( FILE* stream ) ; {\textit{int }}{\textbf{fclose}}{\left({\textit{FILE* }}{\text{stream}}\right)}; int fclose(FILE* stream);
如果文件关闭成功返回数值 0
,如果失败则返回数值 EOF
。
文件访问模式列表
Mode | Description |
---|---|
r | Open a file for reading. |
w | Create a file for writing. If the file already exists, discard the current contents. |
a | Append; open or create a file for writing at the end of the file. |
r+ | Open a file for update(reading and writing). |
w+ | Create a file for update. If the file already exists, discard the current contents. |
a+ | Append: open or create a file for update; writing is done at the end for the file. |
rb | Open a file for reading in binary mode. |
wb | Create a file for writing in binary mode. If the file already exists, discard the current contents. |
ab | Append; open or create a file for writing at the end of file in binary mode. |
rb+ | Open a file for update(reading and writing) in binary mode. |
wb+ | Create a file for update in binary mode. If the file already exists, discard the current contents. |
ab+ | Append: open or create a file for update in binary mode; writing is done at the end of the file. |
用于输入各种计算机系统的 EOF
(end-of-file)的组合键
Operating system | Key combination |
---|---|
UNIX | <return> or [Ctrl] + d |
Windows | [Ctrl] + z |
Macintosh | [Ctrl] + d |
顺序访问文件
顺序访问的文件(Sequential-Access File)
int fprintf ( FILE* steam , const char* format , … ) ; {\textit{int }}{\textbf{fprintf}}{\left({\textit{FILE* }}{\text{steam}},{\textit{const char* }}{\text{format}},\dots\right)}; int fprintf(FILE* steam,