在 C 语言中,文件 I/O(Input/Output)操作是处理文件的重要部分。本文将介绍一些常见的文件 I/O 操作及其使用示例。
fopen()
函数用于打开一个文件。FILE *fptr;
fptr = fopen("filename.txt", "mode");
其中,filename.txt
是文件名,mode
是打开文件的模式,如 “r”(只读),“w”(写入),“a”(追加)等。
fclose()
函数用于关闭文件。fclose(fptr);
使用 fopen
函数可以打开一个文件,并返回一个 FILE
类型的指针,该指针用于后续的文件操作。在完成文件操作后,应使用 fclose
函数关闭文件。
#include
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
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
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
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
都是用于打开文件的函数,但它们有一些关键的区别,主要取决于它们所属的库和用途。fopen
函数:
)。#include
int main() {
FILE *file = fopen("example.txt", "r");
// ...
fclose(file);
return 0;
}
open
函数:
和
)。int
类型),而不是 FILE
指针。#include
#include
#include
#include
int main() {
int fd = open("example.txt", O_RDONLY);
// ...
close(fd);
return 0;
}
总的来说,如果你主要在 C 语言环境下进行文件 I/O 操作,并且希望使用标准 I/O 函数(如fgetc
、fprintf
等),则使用fopen
是更方便的选择。如果你更倾向于使用低级别的文件描述符进行操作,或者需要与 POSIX API 一起使用,则可能更倾向于使用open
。