025. 读写文件内容
写入文件
以下是一个完整的示例,展示如何打开文件、写入内容并关闭文件。
示例:写入文件
#include <stdio.h>
int main() {
FILE *file;
// 打开文件
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;
}
printf("File opened successfully.\n");
// 写入内容
fprintf(file, "Hello, World!\n");
printf("Content written to the file.\n");
// 关闭文件
if (fclose(file) == 0) {
printf("File closed successfully.\n");
} else {
printf("Failed to close the file.\n");
}
return 0;
}
输出结果
File opened successfully.
Content written to the file.
File closed successfully.
文件内容(example.txt
)
Hello, World!
读取文件
以下是一个示例,展示如何打开文件、读取内容并关闭文件。
示例:读取文件
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
// 打开文件
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;
}
printf("File opened successfully.\n");
// 读取内容
if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Content read from the file: %s", buffer);
} else {
printf("Failed to read the file.\n");
}
// 关闭文件
if (fclose(file) == 0) {
printf("File closed successfully.\n");
} else {
printf("Failed to close the file.\n");
}
return 0;
}
输出结果
File opened successfully.
Content read from the file: Hello, World!
File closed successfully.
错误处理
在文件操作中,错误处理非常重要。可以通过检查fopen
和fclose
的返回值来处理错误。
示例:错误处理
#include <stdio.h>
int main() {
FILE *file;
// 打开文件
file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("Failed to open the file");
return 1;
}
printf("File opened successfully.\n");
// 关闭文件
if (fclose(file) == 0) {
printf("File closed successfully.\n");
} else {
perror("Failed to close the file");
}
return 0;
}
输出结果(如果文件不存在)
Failed to open the file: No such file or directory
通过上述示例,你可以看到如何在C语言中错误和读写文件:
- 错误处理:通过检查
fopen
和fclose
的返回值来处理错误。 - 读写文件:可以使用
fprintf
、fscanf
、fgets
、fputs
等函数进行文件读写操作。
视频讲解
BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)