我有这段代码,旨在从文本文件中读取信息,将信息存储在 bin 文件中,然后从 bin 文件中读取信息并将其投影到屏幕上。 我对 bin 文件的写入全部正确,除了当我将 tempStudents 打印到屏幕上时,它总是显示文本文件中的 LAST 选项。所以就好像它拯救的唯一学生就是最后一个学生。
#include<stdlib.h>
#include<stdio.h>
struct student {
char name[200];
float marks;
};
int main() {
FILE * txtFile;
struct student tempStudent;
// File pointer to binary file
FILE * binFile;
int searchNum;
if ((txtFile = fopen("/Users/Ash/Desktop/Lab 8B/input.txt", "r")) == NULL) {
printf("Can not open file input.txt\n");
}
else {
FILE * binFile;
binFile = fopen("/Users/Ash/Desktop/Lab 8B/binFile.bin","w+b");
while (fscanf(txtFile,"%s %f", tempStudent.name, &(tempStudent.marks)) == 2) {
fwrite(tempStudent.name,sizeof(char),sizeof(tempStudent.name),binFile);
fwrite(&tempStudent.marks,sizeof(int),1,binFile);
}
printf("Please enter the student you want to search for\n");
printf("For example if you want the first student type 1\n");
scanf("%d", &searchNum);
int i = 0;
for (i = 0; i <= searchNum; i++)
{
fread(tempStudent.name, 60, sizeof(char),binFile);
fread(&tempStudent.marks,60, sizeof(int),binFile);
}
// write code that reads in the student structure that the user asked for
// from the binary file and store it in the variable tempStudent
printf("The student name retreived is: %s\n", tempStudent.name);
printf("The student mark retreived is: %.2f\n", tempStudent.marks);
fclose(binFile);
fclose(txtFile);
}
return 0;
}
最佳答案
文件具有类似于当前位置的内容。将二进制数据写入文件后,该位置位于末尾。当您(尝试)在此状态下读取 bin 数据时,fread
将读取不到任何内容。
Check the return values!
关于c - fread() 无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23721335/