C语言中使用struct、数组与fwrite写入文件为空问题排查
问题分析与解决
你的代码存在几个关键错误,导致文件为空,逐一说明:
结构体数组越界:定义的
Student student[4];只能容纳4个学生(索引0-3),但你赋值了5个学生(索引0-4),这会触发内存越界,行为未定义,可能导致后续写文件操作异常。应改为struct Student student[5];(标准C中,未用typedef的结构体变量声明必须带struct关键字)。fwrite参数逻辑错误:
fwrite的参数顺序是fwrite(数据指针, 单个元素大小, 元素数量, 文件指针)。你当前的写法:fwrite(student[i].matricule , sizeof(student[i].matricule) , 5 , f);这里
sizeof(student[i].matricule)是指针的大小(32位系统4字节,64位8字节),不是字符串的实际长度;第三个参数传5更是错误——你要写入的是字符串的每个字符,单个元素大小是sizeof(char),元素数量是字符串长度+1(加1是为了写入字符串结束符\0,方便后续读取解析)。正确写法应该用strlen()获取字符串长度。未关闭文件:写完数据后没有调用
fclose(f);,文件缓冲区的内容可能未刷新到磁盘,导致文件显示为空。必须在文件操作完成后关闭文件,确保数据持久化。缺少必要头文件:使用
strlen()需要引入<string.h>头文件,否则可能出现编译错误或未定义行为。
修正后的代码
#include <stdio.h> #include <string.h> int main(){ struct Student { char* matricule; char* nom ; char* prenom; }; struct Student student[5]; student[0].matricule = "m001"; student[0].nom = "Boussaha"; student[0].prenom = "Borhanedine"; student[1].matricule = "m002"; student[1].nom = "Toaba"; student[1].prenom = "Anes"; student[2].matricule = "m003"; student[2].nom = "Laamari"; student[2].prenom = "Loqmane"; student[3].matricule = "m004"; student[3].nom = "Dellachi"; student[3].prenom = "Amir"; student[4].matricule = "m005"; student[4].nom = "Zenfour"; student[4].prenom = "Abdelmouiz"; FILE *f = fopen("list.data" , "wb"); if(f == NULL){ perror("Failed to open file"); return 1; } for (int i = 0; i < 5; i++) { fwrite(student[i].matricule, sizeof(char), strlen(student[i].matricule)+1, f); fwrite(student[i].nom, sizeof(char), strlen(student[i].nom)+1, f); fwrite(student[i].prenom, sizeof(char), strlen(student[i].prenom)+1, f); } fclose(f); return 0; }
内容的提问来源于stack exchange,提问作者borhanedine
相关产品推荐
相关产品推荐

