C语言 fwrite fread 函数怎么使用? 始读取不到数据 也可能我根本没写进去

#include <stdio.h>
#include <string.h>
#define stuSize 1 // define的时候 没有数据类型 也不用写; 符号!!!

void saveToDisk(char path[32]);
void checkFile(char path[32]);

typedef struct Stu {
char stuname[20];
int no;
int age;
} Stu;
Stu stus[20];
Stu stud[20];
void main() {

Stu a;

a.no = 11;
strcpy(a.stuname, "sss");
a.age = 1;
stus[0] = a;

char path[] = "D:/123123";
saveToDisk(path);
checkFile(path);
}

void saveToDisk(char path[32]) {

FILE *fp;
if ((fp = fopen(path, "wb")) == NULL ) { //wb write binary 写二进制文件
printf("%s", "can nnot find file");
return;
}
int i = 0;
for (i = 0; i < 1; i++) {
if (fwrite(&stus[i], sizeof(struct Stu), 1, fp) != 1)
{
printf("%s", "write error");
}
}
}

void checkFile(char path[32]) {//读取数据的时候 想把读到的数据放在stud数组中

FILE *fp;
if ((fp = fopen(path, "rb")) == NULL ) {
printf("%s", "wrong!!");
}
int i = 0;
for (i = 0; i < 1; i++) {
fread(&stud[i], sizeof(struct Stu), 1, fp);
printf("%s,%d,%d,%s\n", stud[i].stuname, stud[i].no, stud[i].age);
}
}

C语言里的fwrite,是带写缓冲的。
你往文件里写数据后,数据并不是马上就写到文件里。主要在下面三种情况下会写到文件里:
(1)缓冲区满了
(2)使用了fflush函数
(3)使用了fclose函数
所以你的错误就在于,在saveToDisk函数的最后,没有把文件关闭。
另外,对文件操作结束,把文件关闭掉本身就是个好习惯。
void saveToDisk(char path[32]) {
FILE *fp;
if ((fp = fopen(path, "wb")) == NULL ) { //wb write binary 写二进制文件
printf("%s", "can nnot find file");
return;
}
int i = 0;
for (i = 0; i < 1; i++) {
if (fwrite(&stus[i], sizeof(struct Stu), 1, fp) != 1)
{
printf("%s", "write error");
}
}
fclose(fp);

}

void checkFile(char path[32]) {//读取数据的时候 想把读到的数据放在stud数组中

FILE *fp;
if ((fp = fopen(path, "rb")) == NULL ) {
printf("%s", "wrong!!");
}
int i = 0;
for (i = 0; i < 1; i++) {
fread(&stud[i], sizeof(struct Stu), 1, fp);
printf("%s,%d,%d,%s\n", stud[i].stuname, stud[i].no, stud[i].age);
}
fclose(fp);

}
温馨提示:答案为网友推荐,仅供参考
相似回答