fopen, fopen_s
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |   定义于头文件  <stdio.h>
  | 
||
| (1) | ||
|   FILE *fopen( const char *filename, const char *mode );  | 
(C99 前) | |
|   FILE *fopen( const char *restrict filename, const char *restrict mode );  | 
(C99 起) | |
|   errno_t fopen_s(FILE *restrict *restrict streamptr,                 const char *restrict filename,  | 
(2) | (C11 起) | 
1) 打开 
filename 所指示的文件,并返回指向关联到该文件的文件流的指针。 mode 用于确定文件访问模式。2) 同(1),除了指向文件流的指针被写入 
streamptr ,还在运行时检测下列错误,并调用当前安装的制约处理函数:
-  
streamptr是空指针 -  
filename是空指针 -  
mode是空指针 
-  
 - 同所有边界检查函数, 
fopen_s仅若实现定义了 __STDC_LIB_EXT1__ ,且用户在包含<stdio.h>前定义 __STDC_WANT_LIB_EXT1__ 为整数常量 1 才保证可用。 
参数
| filename | - | 关联到文件系统的文件名 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
| mode | - |   确定访问模式的空终止字符串
  | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
| streamptr | - | 指向存储函数结果的指针的指针(输出参数) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
返回值
2) 若成功,则返回零并将新文件流指针写入 
*streamptr 。错误时,返回非零错误码并将空指针写入 *streamptr (除非 streamptr 自身也是空指针)。注意
filename 的格式是实现定义的,而且不需要表示一个文件(譬如可以是控制台或另一能通过文件系统 API 访问的设备)。在支持的平台上, filename 可以包含绝对或相对路径。
示例
运行此代码
#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; // 注意:int,非char,要求处理EOF while ((c = fgetc(fp)) != EOF) { // 标准C I/O读取文件循环 putchar(c); } if (ferror(fp)) puts("I/O error when reading"); else if (feof(fp)) puts("End of file reached successfully"); fclose(fp); }
 
引用
- C11 standard (ISO/IEC 9899:2011):
 
- 7.21.5.3 The fopen function (p: 305-306)
 
- K.3.5.2.1 The fopen_s function (p: 588-590)
 
- C99 standard (ISO/IEC 9899:1999):
 
- 7.19.5.3 The fopen function (p: 271-272)
 
- C89/C90 standard (ISO/IEC 9899:1990):
 
- 4.9.5.3 The fopen function
 
参阅
|    关闭文件   (函数)  | |
|    将输出流与实际文件同步  (函数)  | |
|    (C11)  | 
   以不同名称打开既存的文件流  (函数)  |