C语言读取文件首行与输入对比及保留首行方法咨询
C语言文件操作问题解答
问题1:读取文件第一行并与输入内容对比
- 定义足够大的字符缓冲区存储读取的行内容,注意
fgets会保留换行符\n,对比前需要去除(可借助strcspn函数)。 - 以读模式
"r"打开文件,必须判断文件是否成功打开。 - 用
fgets读取第一行,读取成功后与输入内容用strcmp做字符串对比。 - 操作完成后务必关闭文件。
示例代码片段:
#include <stdio.h> #include <string.h> int main() { char input[] = "123"; char buf[100]; FILE *fptr = fopen("text.txt", "r"); if (fptr == NULL) { perror("Failed to open file"); return 1; } if (fgets(buf, sizeof(buf), fptr) != NULL) { // 去除换行符 buf[strcspn(buf, "\n")] = '\0'; if (strcmp(buf, input) == 0) { printf("内容匹配\n"); } else { printf("内容不匹配\n"); } } fclose(fptr); return 0; }
问题2:写入表格数据时保持第一行不变
核心思路是先把第一行内容暂存到内存,再重新写入文件:
- 以读模式打开文件,读取第一行并存储到内存变量中;如果文件为空,可自定义默认表头。
- 以写模式
"w"打开文件(会清空原文件),先写入之前保存的第一行内容。 - 接着写入新的表格数据。
- 若要避免写入过程中文件损坏,可先写入临时文件,全部完成后替换原文件(更安全)。
示例代码:
#include <stdio.h> #include <string.h> int main() { char first_line[100]; FILE *fptr; // 读取第一行 fptr = fopen("text.txt", "r"); if (fptr == NULL) { perror("Failed to open file for reading"); return 1; } if (fgets(first_line, sizeof(first_line), fptr) == NULL) { // 文件为空时设置默认表头 strcpy(first_line, "表头列1\t表头列2\t表头列3\n"); } fclose(fptr); // 写入原第一行+新表格数据 fptr = fopen("text.txt", "w"); if (fptr == NULL) { perror("Failed to open file for writing"); return 1; } fputs(first_line, fptr); // 写入示例表格数据 fprintf(fptr, "数据1\t数据2\t数据3\n"); fprintf(fptr, "100\t200\t300\n"); fclose(fptr); return 0; }
你的代码中的错误修正
- 头文件拼写错误:
<sting.h>改为<string.h> - 关键字拼写错误:
ỉnt改为int fgets参数错误:第一个参数必须是可写的字符缓冲区,不能是字符串常量"123",需定义数组存储读取内容- 文件打开模式错误:写入操作需用
"w"/"a"模式,"r"模式无法写入文件 - 逻辑疏漏:对比前未处理换行符,重复打开文件未做错误判断
修正后的基础逻辑代码:
#include <stdio.h> #include <string.h> int main() { FILE *fptr; char buf[100]; // 打开文件读取第一行 fptr = fopen("text.txt", "r"); if (fptr == NULL) { // 文件不存在则创建并写入"123" fptr = fopen("text.txt", "w"); if (fptr != NULL) { fprintf(fptr, "123"); fclose(fptr); } return 1; } // 读取第一行并处理换行符 if (fgets(buf, sizeof(buf), fptr) != NULL) { buf[strcspn(buf, "\n")] = '\0'; if (strcmp(buf, "123") != 0) { fclose(fptr); // 打开文件写入"123" fptr = fopen("text.txt", "w"); if (fptr != NULL) { fprintf(fptr, "123"); fclose(fptr); } } else { fclose(fptr); } } return 0; }
内容的提问来源于stack exchange,提问作者BiBeoLovesCoding
相关产品推荐
相关产品推荐

