Advertisement

C语言文档阅读笔记-Basics of File Handling in C

阅读量:

在学习C语言的过程中,主要局限于在控制台进行数据展示,而真实软件开发过程中则需要将部分数据存储起来,从而引出了对文件的读取与写入过程的研究.对于这一系列操作,我们首先要了解其基本原理以及实现方法

①创建一个文件(fopen并且可以使用的模式为a、a+、w、w+)。

②打开文件(fopen)。

③读取文件(fscanf或fgets)。

④写入文件(fprintf或fputs)。

⑤移动文件指针到指定的位置(fseek、rewind)。

⑥关闭文件(fclose)。

下面的表描述了各个函数的基本说明:

这里我也来解释下吧:

文件操作 声明和描述

| fopen():打开文件| 声明:FILE *fopen(const char *filename, const char *mode)
fopen()函数用于打开或创建一个文件指针,并根据指定的模式进行操作,在C语言程序中通常会先调用fopen函数获取文件指针对象。如果指定的文件路径不存在,则会创建一个新的空文件对象存放所需内容;
如下代码:
FILE *fp;
fp = fopen("filename", "mode");
fp:指向所打开/创建的文件指针类型;
filename:可以是绝对路径也可以是相对路径;
mode参数决定了对当前文件的操作模式,默认情况下支持r(读)、w(写)、a(追加)等基本操作;后面会详细讲解每种具体的操作模式及其应用场景; |
| fclose():关闭文件| 声明:int fclose(FILE *fp)
该函数用于关闭已打开或已存在的文件指针对象,在编程实践当中应当在每次成功获取到新的文件指针后立即调用此函数以释放资源并防止数据丢失; |
| fgets():按行读取指定文件| 声明:char *fgets(char *buffer, int length, FILE *file)
此函数用于从标准输入流中逐行读取指定长度的数据到目标缓冲区中,并返回所读取的内容长度值;实现方式如下:
char buffer[1024];
int count = fgets(buffer, sizeof(buffer), fp);
if (count == -1) {
// 已到达 EOF
}
// 以此类推 |
| fprintf():输出到文件中| 声明:int fprintf(FILE *file, const char *format, ...)
该函数用于将格式化后的数据输出到目标流中,在实际编程应用当中常与printf函数配合使用以实现复杂的数据显示需求;实现方法包括:
int status = fprintf(fp, "test: %d", testNumber);
if (status != EOF) {
// 成功输出
}
// 类似地 |

打开或创建文件

通过fopen()第二个参数可以指定对文件操作的模式如下:

r:打开只读文件,当文件存在返回文件指针,否则返回NULL。

rb:通过二进制格式解码只读文件,在此操作成功时将返回指向该文件的指针;如果无法解码,则返回NULL。

w:打开一个只能进行写入操作的文本文件;当该文件已存在时,则会清除其当前内容;若该文件不存在,则会新建一个空白文档;否则将返回无数据记录。

wb:按照二进制的方式打开专用于只编写目的的文件;若该文件已存在,则会清除其内容;若未找到该文件,则生成新文件;若无法创建则返回NULL

a:通过附加方式打开只读文件。若成功则返回文件末尾位置;若不存在则生成新文件;否则返回NULL指针。

ab:通过二进制追加的方式打开只读文件;当操作成功时会将数据写到文件末尾的位置;如果原文件不存在,则会新建一个空白文件;但如果无法创建,则返回NULL值。

r+:打开可读可写文件,当文件存在返回文件指针,否则返回NULL。

rb+:按二进制方式打开可读且可写的二进制文件;如果该文件存在,则返回指向该文件的指针;否则返回NULL

w+:打开一个兼有可读性和可写的属性的文件,并将该文件的内容重置为空;若该文件不存在,则生成一个新的空白文件;若无法找到该路径,则返回NULL。

wb+:通过二进制方式打开具有可读性和写的属性的文件;当目标文件已存在时,则会清除其当前内容;若未找到该目标文件,则会生成一个新的空白文件;在无法执行上述操作的情况下(如无法定位或创建新文件),则返回NULL值。

a+:以附加功能打开支持读写操作的文件,并在成功时返回其末尾位置;当该文件不存在时生成新的文件;若无法创建则返回NULL。

ab+:通过二进制追加的方式打开已有的可读且可写的二进制文件,并将结果写在其末尾位置;若原文件不存在,则创建新文件;若无法创建,则返回NULL。

在处理二进制文件时,在最后添加"b"字符就可以实现目标效果了。例如将命令中的"w"替换为"wb"或者将命令中的"a+"替换为"a+b"就可以达到预期效果

比如如下调用方式:

复制代码
 FILE *filePointer;

    
  
    
 So, the file can be opened as 
    
  
    
 filePointer = fopen("fileName.txt", "w")
    
    
    
    
    cpp

从文件中读取数据

可以使用fsanf和fgets这两个函数读取文件数据,如下代码:

复制代码
 FILE * filePointer;

    
  
    
 filePointer = fopen("fileName.txt", "r");
    
  
    
 fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
    
    
    
    
    cpp

写文件

可以使用fprintf和fputs如下代码:

复制代码
 FILE *filePointer ;

    
  
    
 filePointer = fopen("fileName.txt", "w");
    
  
    
 fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
    
    
    
    
    cpp

关闭文件

当对文件操作完成后就要关闭文件,代码如下:

复制代码
 FILE *filePointer ;

    
  
    
 filePointer= fopen("fileName.txt", "w");
    
  
    
 ---------- Some file Operations -------
    
  
    
 fclose(filePointer)
    
    
    
    
    cpp

例子1:打开文件,写文件,然后关闭。

复制代码
 // C program to Open a File,

    
 // Write in it, And Close the File
    
  
    
 # include <stdio.h>
    
 # include <string.h>
    
  
    
 int main( )
    
 {
    
  
    
 	// Declare the file pointer
    
 	FILE *filePointer ;
    
 	
    
 	// Get the data to be written in file
    
 	char dataToBeWritten[50]
    
 		= "GeeksforGeeks-A Computer Science Portal for Geeks";
    
  
    
 	// Open the existing file GfgTest.c using fopen()
    
 	// in write mode using "w" attribute
    
 	filePointer = fopen("GfgTest.c", "w") ;
    
 	
    
 	// Check if this filePointer is null
    
 	// which maybe if the file does not exist
    
 	if ( filePointer == NULL )
    
 	{
    
 		printf( "GfgTest.c file failed to open." ) ;
    
 	}
    
 	else
    
 	{
    
 		
    
 		printf("The file is now opened.\n") ;
    
 		
    
 		// Write the dataToBeWritten into the file
    
 		if ( strlen ( dataToBeWritten ) > 0 )
    
 		{
    
 			
    
 			// writing in the file using fputs()
    
 			fputs(dataToBeWritten, filePointer) ;
    
 			fputs("\n", filePointer) ;
    
 		}
    
 		
    
 		// Closing the file using fclose()
    
 		fclose(filePointer) ;
    
 		
    
 		printf("Data successfully written in file GfgTest.c\n");
    
 		printf("The file is now closed.") ;
    
 	}
    
 	return 0;	
    
 }
    
    
    
    
    cpp
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/bEp2sNuJ6S8qmoRQHO0jLcDXVkUY.png)

例2:打开文件,读文件,然后关闭。

复制代码
 // C program to Open a File,

    
 // Read from it, And Close the File
    
  
    
 # include <stdio.h>
    
 # include <string.h>
    
  
    
 int main( )
    
 {
    
  
    
 	// Declare the file pointer
    
 	FILE *filePointer ;
    
 	
    
 	// Declare the variable for the data to be read from file
    
 	char dataToBeRead[50];
    
  
    
 	// Open the existing file GfgTest.c using fopen()
    
 	// in read mode using "r" attribute
    
 	filePointer = fopen("GfgTest.c", "r") ;
    
 	
    
 	// Check if this filePointer is null
    
 	// which maybe if the file does not exist
    
 	if ( filePointer == NULL )
    
 	{
    
 		printf( "GfgTest.c file failed to open." ) ;
    
 	}
    
 	else
    
 	{
    
 		
    
 		printf("The file is now opened.\n") ;
    
 		
    
 		// Read the dataToBeRead from the file
    
 		// using fgets() method
    
 		while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
    
 		{
    
 		
    
 			// Print the dataToBeRead
    
 			printf( "%s" , dataToBeRead ) ;
    
 		}
    
 		
    
 		// Closing the file using fclose()
    
 		fclose(filePointer) ;
    
 		
    
 		printf("Data successfully read from file GfgTest.c\n");
    
 		printf("The file is now closed.") ;
    
 	}
    
 	return 0;	
    
 }
    
    
    
    
    cpp
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/ySdQeGT8p1tIVA2oUzK7fucN4jsP.png)

例3:使用fwrite写二进制文件。

复制代码
 #include <stdio.h>

    
 #include <stdlib.h>
    
 struct threeNum
    
 {
    
 int n1, n2, n3;
    
 };
    
 int main()
    
 {
    
 int n;
    
 struct threeNum num;
    
 FILE *fptr;
    
 if ((fptr = fopen("C:\ program.bin","wb")) == NULL){
    
 printf("Error! opening file");
    
 // Program exits if the file pointer returns NULL.
    
 exit(1);
    
 }
    
 for(n = 1; n < 5; ++n) //Program Code Submitted by Susobhan Akhuli
    
 {
    
 num.n1 = n;
    
 num.n2 = 5*n;
    
 num.n3 = 5*n + 1;
    
 fwrite(&num, sizeof(struct threeNum), 1, fptr);
    
 }
    
 fclose(fptr);
    
 return 0;
    
 }
    
    
    
    
    cpp
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/X6DaHd2hIsERvFglMriGBNmO08t5.png)

例4:使用fread()读二进制文件。

复制代码
 #include <stdio.h>

    
 #include <stdlib.h>
    
 struct threeNum
    
 {
    
 int n1, n2, n3;
    
 };
    
 int main()
    
 {
    
 int n;
    
 struct threeNum num;
    
 FILE *fptr;
    
 if ((fptr = fopen("C:\ program.bin","rb")) == NULL){
    
 printf("Error! opening file");
    
 // Program exits if the file pointer returns NULL.
    
 exit(1);
    
 }
    
 for(n = 1; n < 5; ++n) //Program Code Submitted by Susobhan Akhuli
    
 {
    
 fread(&num, sizeof(struct threeNum), 1, fptr);
    
 printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
    
 }
    
 fclose(fptr);
    
  
    
 return 0;
    
 }
    
    
    
    
    cpp
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/kT3ogW2shjz8nFq4NR7caACpIZOY.png)

全部评论 (0)

还没有任何评论哟~