在C语言中,文件操作是编程中的一个重要部分,通过文件操作,我们可以将数据存储到磁盘上,或者从磁盘读取数据,这为数据的持久化和程序间的数据交换提供了便利,本文将详细介绍如何在C语言中进行文件的打开、写入和读取等基本操作。
打开文件
在C语言中,使用fopen()
函数来打开文件,这个函数的原型位于头文件stdio.h
中:
FILE *fopen(const char *filename, const char *mode);
- 参数:
filename
: 要打开的文件名(包括路径)。mode
: 指定打开模式,如"r"
(只读)、"w"
(写入)、"a"
(追加)等。
示例代码如下:
#include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); if (fp == NULL) { printf("无法打开文件\n"); return 1; } // 写入数据到文件 fprintf(fp, "Hello, World!\n"); // 关闭文件 fclose(fp); return 0; }
写入文件
一旦成功打开了文件,就可以向文件中写入数据了,常用的函数有fprintf()
和fputs()
。
图片来源于网络,如有侵权联系删除
使用fprintf()
函数
fprintf()
函数用于格式化输出到文件中,类似于printf()
函数:
int fprintf(FILE *stream, const char *format, ...);
示例代码如下:
#include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); if (fp == NULL) { printf("无法打开文件\n"); return 1; } // 写入多个数据到文件 fprintf(fp, "Line 1: Hello, World!\n"); fprintf(fp, "Line 2: This is a test.\n"); // 关闭文件 fclose(fp); return 0; }
使用fputs()
函数
fputs()
函数用于直接写入字符串到文件中:
int fputs(const char *str, FILE *stream);
示例代码如下:
#include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); if (fp == NULL) { printf("无法打开文件\n"); return 1; } // 写入字符串到文件 fputs("This is another line.\n", fp); // 关闭文件 fclose(fp); return 0; }
读取文件
要读取文件中的数据,可以使用fscanf()
或fgets()
函数。
使用fscanf()
函数
fscanf()
函数用于格式化输入,类似于scanf()
函数:
图片来源于网络,如有侵权联系删除
int fscanf(FILE *stream, const char *format, ...);
示例代码如下:
#include <stdio.h> int main() { FILE *fp; char str[100]; int num; fp = fopen("example.txt", "r"); if (fp == NULL) { printf("无法打开文件\n"); return 1; } // 读取整数和字符串 fscanf(fp, "%d %s", &num, str); printf("Read from file: %d %s\n", num, str); // 关闭文件 fclose(fp); return 0; }
使用fgets()
函数
fgets()
函数用于读取一行文本:
char *fgets(char *str, int n, FILE *stream);
示例代码如下:
#include <stdio.h> int main() { FILE *fp; char str[100]; fp = fopen("example.txt", "r"); if (fp == NULL) { printf("无法打开文件\n"); return 1; } // 读取一行文本 fgets(str, sizeof(str), fp); printf("Read from file: %s\n", str); // 关闭文件 fclose(fp); return 0; }
处理文件指针
在使用完文件后,应该关闭文件以释放资源,可以通过fclose()
函数来实现:
int fclose(FILE *stream);
示例代码如下:
#include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "r"); if (fp == NULL) { printf("无法打开文件\n"); return 1; } //
标签: #文件的保存c语言
评论列表