C语言修改结构体后写入文件出现编码异常的问题求助
问题分析与解决方案
核心问题
你的代码写入文件时存在两个致命错误:
- 使用**二进制写入
fwrite**直接输出结构体的内存原始数据,而非原文件的CSV文本格式,导致文本编辑器无法解析二进制数据,出现乱码。 fwrite仅写入了1个结构体,没有遍历所有读取到的records条数据。
另外还有一段冗余代码:if (students[i].name == students[i].name)是恒成立的无意义判断,可直接删除。
修正后的代码
#include <stdio.h> #include <string.h> typedef struct { char type; char name[50]; char surname[50]; } Student; int main(void) { FILE *file; // 读取CSV文件数据 file = fopen("file.txt", "r"); if (file == NULL) { printf("Error opening file.\n"); return 1; } Student students[100]; int records = 0; while (fscanf(file, " %c , %49[^,], %49[^,],", &students[records].type, students[records].name, students[records].surname) == 3) { records++; if (ferror(file)) { printf("Error reading file.\n"); return 1; } } fclose(file); printf("\n%d records read.\n\n", records); for (int i = 0; i < records; i++) printf("%c %s %s\n", students[i].type, students[i].name, students[i].surname); printf("\n"); // 修改第一条记录的name字段 strcpy(students[0].name, "Elena Heis"); printf("修改后第一条记录name: %s\n", students[0].name); // 以文本模式写入CSV格式数据 file = fopen("file.txt", "w"); if (file != NULL) { // 遍历所有记录,按原CSV格式写入 for (int i = 0; i < records; i++) { fprintf(file, "%c,%s,%s,\n", students[i].type, students[i].name, students[i].surname); } fclose(file); } return 0; }
关键修正点
- 写入方式替换:将二进制
fwrite改为文本fprintf,严格遵循原文件的类型,名字,姓氏,格式输出每条记录。 - 遍历所有记录:通过循环把所有
records条数据写入文件,避免只写入单条数据的问题。 - 文件打开模式修正:使用文本模式
"w"而非二进制"wb",确保写入内容为可解析的文本格式。 - 冗余代码清理:删除无意义的恒真判断,直接修改目标记录。
预期写入效果
修改后,file.txt会恢复正常CSV格式,第一条记录的name字段更新为Elena Heis,内容如下:
U,Elena Heis,Virat Kohli, U,Serena Williams,Virat Kohli, G,Wayne Gretzky,Virat Kohli, U,Virat Kohli,Virat Kohli, U,Serena Williams,Virat Kohli, G,Wayne Gretzky,Virat Kohli,
内容的提问来源于stack exchange,提问作者GPB
相关产品推荐
相关产品推荐

