非常教程

C参考手册

文件输入/输出 | File input/output

fopen

在头文件<stdio.h>中定义

(1)

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

(直到C99)

FILE * fopen(const char *限制文件名,const char *限制模式);

(自C99以来)

errno_t fopen_s(FILE * restrict *限制streamptr,const char *限制文件名,const char *限制模式);

(2)

(自C11以来)

1)打开由该文件指示的文件filename并返回指向与该文件关联的文件流的指针。mode用于确定文件访问模式。

2)与(1)相同,除了写入指向文件流的指针streamptr以及在运行时检测到以下错误并调用当前安装的约束处理函数:

  • streamptr 是一个空指针
  • filename 是一个空指针
  • mode 是一个空指针

作为所有边界检查函数,fopen_s只有在被__STDC_LIB_EXT1__实现定义__STDC_WANT_LIB_EXT1__并且1在包含之前用户定义为整数常量时才能保证可用<stdio.h>

参数

文件名

-

将文件流关联到的文件名

模式

-

null-terminated character string determining file access mode File access mode string Meaning Explanation Action if file already exists Action if file does not exist "r" read Open a file for reading read from start failure to open "w" write Create a file for writing destroy contents create new "a" append Append to a file write to end create new "r+" read extended Open a file for read/write read from start error "w+" write extended Create a file for read/write destroy contents create new "a+" append extended Open a file for read/write write to end create new File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has effect only on Windows systems. On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator. When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations. File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C11) When using fopen_s or freopen_s, file access permissions for any file created with "w" or "a" prevents other users from accessing it. File access mode flag "u" can optionally be prepended to any specifier that begins with "w" or "a", to enable the default fopen permissions. (C11)

File access mode string

Meaning

Explanation

Action if file already exists

Action if file does not exist

"r"

read

Open a file for reading

read from start

failure to open

"w"

write

Create a file for writing

destroy contents

create new

"a"

append

Append to a file

write to end

create new

"r+"

read extended

Open a file for read/write

read from start

error

"w+"

write extended

Create a file for read/write

destroy contents

create new

"a+"

append extended

Open a file for read/write

write to end

create new

File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has effect only on Windows systems. On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.

File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C11)

当使用fopen_s或freopen_s时,用“w”或“a”创建的任何文件的文件访问权限会阻止其他用户访问它。文件访问模式标志“u”可以有选择地添加到以“w”或“a”开头的任何说明符中,以启用默认的fopen权限。(C11)

文件访问模式字符串

含义

说明

行动如果文件已经存在

如果文件不存在,则采取行动

“R”

打开一个文件以供阅读

从开始阅读

未能打开

“W”

创建一个文件写入

破坏内容

创建新的

“一个”

附加

附加到文件

写入结束

创建新的

“R +”

阅读扩展

打开文件进行读取/写入

从开始阅读

错误

“W +”

写入扩展

创建一个用于读/写的文件

破坏内容

创建新的

“A +”

追加扩展

打开文件进行读取/写入

写入结束

创建新的

| 可以选择指定文件访问模式标志“b”以二进制模式打开文件。该标志只对Windows系统有效。在附加文件访问模式下,无论文件位置指示符的当前位置如何,数据都会写入文件末尾。|

| 当以更新模式('+'作为上述模式参数值列表中的第二个或第三个字符)打开文件时,可以在关联的流上执行输入和输出。然而,输出不应直接跟随输入而没有插入调用fflush函数或文件定位函数(fseek,fsetpos,或倒带),并且输入不应直接跟随输出而没有中间呼叫到一个文件中的定位函数,除非输入操作遇到文件结束。在某些实现中打开(或创建)具有更新模式的文本文件可能会打开(或创建)二进制流。|

| 文件访问模式标志“x”可以选择性地附加到“w”或“w +”说明符。如果文件存在,该标志强制该功能失败,而不是覆盖它。(C11)|

| 当使用fopen_s或freopen_s时,用“w”或“a”创建的任何文件的文件访问权限会阻止其他用户访问它。文件访问模式标志“u”可以有选择地添加到以“w”或“a”开头的任何说明符中,以启用默认的fopen权限。(C11)|

| streamptr | - | 指向函数存储结果的指针(out-parameter)|的指针

返回值

1)如果成功,返回一个指向新文件流的指针。除非filename指向交互式设备,否则该流完全缓冲。出错时,返回一个null pointer。POSIX需要的是errno在这种情况下设置。

2)如果成功,则返回零,并写入指向新文件流的指针*streamptr。出错时,返回一个非零的错误代码并将空指针写入*streamptr(除非streamptr是空指针本身)。

注意

格式filename是实现定义的,并不一定是指文件(例如它可能是控制台或通过文件系统API可访问的其他设备)。在支持它们的平台上,filename可能包括绝对或相对的文件系统路径。

Example

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    FILE* fp = fopen("test.txt", "r");
    if(!fp) {
        perror("File opening failed");
        return EXIT_FAILURE;
    }
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) { // standard C I/O file reading loop
       putchar(c);
    }
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp))
        puts("End of file reached successfully");
 
    fclose(fp);
}

参考

  • C11标准(ISO / IEC 9899:2011):
    • 7.21.5.3 fopen函数(p:305-306)
    • K.3.5.2.1 fopen_s函数(p:588-590)
  • C99标准(ISO / IEC 9899:1999):
    • 7.19.5.3 fopen函数(p:271-272)
  • C89 / C90标准(ISO / IEC 9899:1990):
    • 4.9.5.3 fopen函数
C

C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。