好的,让我们更详细地探讨C语言中的文件读写操作。下面的示例将包括文件的打开、写入、读取、定位、关闭等操作,以及相关的错误处理。
文件打开
首先,你需要打开一个文件以进行读写操作。fopen函数用于打开文件,并返回一个指向FILE对象的指针。
FILE *fp;
// 用写模式打开"output.txt",如果文件不存在则创建
fp = fopen("output.txt", "w");
if (fp == NULL) {
fprintf(stderr, "Error opening file!\n");
return EXIT_FAILURE;
}
写入文件
写入字符串
// 写入字符串到文件
const char *text = "Hello, this is a test string.\n";
fputs(text, fp);
写入格式化数据
// 使用格式化输出写入数据,类似于printf
int num = 123;
fprintf(fp, "The number is: %d\n", num);
二进制写入
如果要写入二进制数据,可以使用fwrite:
// 假设我们有一个整数数组
int numbers[] = {1, 2, 3, 4, 5};
size_t count = sizeof(numbers) / sizeof(numbers[0]);
// 写入整个数组到文件
fwrite(numbers, sizeof(int), count, fp);
读取文件
读取字符串
// 读取一行文本到字符串
char buffer[100];
fgets(buffer, sizeof(buffer), fp);
printf("Read line: %s", buffer);
读取格式化数据
// 从文件中读取格式化数据
int num;
fscanf(fp, "The number is: %d\n", &num);
printf("Read number: %d", num);
读取二进制数据
使用fread来读取二进制数据:
// 读取二进制数据到数组
int read_numbers[count];
size_t read_count = fread(read_numbers, sizeof(int), count, fp);
// 检查是否成功读取
if (read_count != count) {
fprintf(stderr, "Error reading from file\n");
}
文件定位
fseek函数用于移动文件位置指针,ftell用于获取当前文件位置。
// 移动到文件开头,从开头计算偏移量0
fseek(fp, 0, SEEK_SET);
// 获取当前文件位置
long position = ftell(fp);
printf("Current file position: %ld\n", position);
文件结束检测
使用feof函数检查是否到达文件末尾。
if (feof(fp)) {
printf("End of file reached.\n");
}
错误检查
使用ferror函数检查文件操作是否发生错误。
if (ferror(fp)) {
fprintf(stderr, "Error occurred during file operation.\n");
}
关闭文件
操作完成后,使用fclose函数关闭文件。
// 关闭文件
if (fclose(fp) != 0) {
fprintf(stderr, "Error closing file.\n");
return EXIT_FAILURE;
}
完整示例:文件写入和读取
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char write_buf[] = "Hello, World! This is a test file.\n";
char read_buf[50];
size_t len;
// 打开文件用于写入
fp = fopen("test.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
// 写入字符串
fputs(write_buf, fp);
// 关闭文件
fclose(fp);
// 重新打开文件用于读取
fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
// 读取数据
len = fread(read_buf, sizeof(char), sizeof(write_buf), fp);
if (len > 0) {
read_buf[len] = '\0'; // 确保字符串以空字符结尾
printf("Read from file: %s", read_buf);
}
// 关闭文件
fclose(fp);
return EXIT_SUCCESS;
}
这个例子展示了如何打开一个文件用于写入,写入一个字符串,关闭文件,然后重新打开文件用于读取,读取数据,并打印到控制台。最后,关闭文件并正常退出程序。在实际编程中,你需要根据实际需求调整文件操作的细节。