文件 I/O 操作在 C 语言中的使用
在 C 语言中,文件 I/O(Input/Output)操作是处理文件的重要部分。本文将介绍一些常见的文件 I/O 操作及其使用示例。
打开和关闭文件
1.打开文件:
- fopen()函数用于打开一个文件。
FILE *fptr;
fptr = fopen("filename.txt", "mode");
其中,filename.txt 是文件名,mode 是打开文件的模式,如 “r”(只读),“w”(写入),“a”(追加)等。
2.关闭文件
- fclose()函数用于关闭文件。
fclose(fptr);
使用 fopen 函数可以打开一个文件,并返回一个 FILE 类型的指针,该指针用于后续的文件操作。在完成文件操作后,应使用 fclose 函数关闭文件。
#include <stdio.h>int main() {FILE *file = fopen("example.txt", "w");if (file == NULL) {printf("无法打开文件。\n");return 1;}// 在此进行文件操作fclose(file);return 0;
}
读取文件
- fgetc()用于逐个字符读取文件。
int ch;
ch = fgetc(fptr);
- fgets()用于逐行读取文件。
char buffer[255];
fgets(buffer, sizeof(buffer), fptr);
- fscanf()用于按格式从文件读取数据。
int num;
fscanf(fptr, "%d", &num);
#include <stdio.h>int main() {FILE *fptr;char ch;fptr = fopen("example.txt", "r"); // 打开文件以进行读取if (fptr == NULL) {printf("无法打开文件。\n");return 1;}// 逐个字符读取文件while ((ch = fgetc(fptr)) != EOF) {printf("%c", ch);}fclose(fptr);return 0;
}
写入文件
- fputc()用于逐个字符写入文件。
fputc('A', fptr);
- fputs()用于写入字符串到文件。
fputs("Hello, World!", fptr);
- fprintf()用于按格式向文件写入数据。
int num = 42;
fprintf(fptr, "The number is: %d", num);
#include <stdio.h>int main() {FILE *fptr;fptr = fopen("example.txt", "w"); // 打开文件以进行写入if (fptr == NULL) {printf("无法打开文件。\n");return 1;}// 向文件写入字符串fprintf(fptr, "Hello, World!\n");fclose(fptr);return 0;
}
文件位置指针
- fseek()用于设置文件位置指针的位置。
fseek(fptr, offset, SEEK_SET);
其中,offset 是偏移量,SEEK_SET 表示相对于文件开头。
- ftell()用于获取文件位置指针的当前位置。
long position = ftell(fptr);
#include <stdio.h>int main() {FILE *fptr;fptr = fopen("example.txt", "r"); // 打开文件以进行读取if (fptr == NULL) {printf("无法打开文件。\n");return 1;}fseek(fptr, 5, SEEK_SET); // 将文件指针移动到文件开头的第 5 个字节处char ch;while ((ch = fgetc(fptr)) != EOF) {printf("%c", ch);}fclose(fptr);return 0;
}
fopen 和 open 都是用于打开文件的函数,但它们有一些关键的区别,主要取决于它们所属的库和用途。
 
1.fopen函数:
 
- 属于标准 C 库(<stdio.h>)。
- 用于以标准 I/O 流的形式打开文件。
- 返回一个 FILE 类型的指针,该指针可用于后续的文件 I/O 操作。
- 例如:
#include <stdio.h>int main() {FILE *file = fopen("example.txt", "r");// ...fclose(file);return 0;
}
2.open函数:
 
- 属于 POSIX 标准库(<fcntl.h>和<sys/stat.h>)。
- 用于更底层的文件操作,提供对文件描述符的直接访问。
- 返回一个文件描述符(int类型),而不是FILE指针。
- 例如:
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>int main() {int fd = open("example.txt", O_RDONLY);// ...close(fd);return 0;
}
总的来说,如果你主要在 C 语言环境下进行文件 I/O 操作,并且希望使用标准 I/O 函数(如fgetc、fprintf 等),则使用fopen 是更方便的选择。如果你更倾向于使用低级别的文件描述符进行操作,或者需要与 POSIX API 一起使用,则可能更倾向于使用open。