c - fread() 无法正常工作?

标签 c

我有这段代码,旨在从文本文件中读取信息,将信息存储在 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/

相关文章:

c - ioctl调用程序编译错误

c - 在 C 中有效使用 goto 进行错误管理?

c - Microsoft Visual C++ Express 中的 Lotus C API 示例

c - 简单的 C 程序在 Eclipse 中不显示输出

c - printf() 未打印正确的计算结果

c - 两个随机数组

c - 需要 : Wrappable Counter where < and > do "the right thing"

c++ - 初始化结构中的常量数组

C Language : trouble using enumerated variable and type definited in main. c文件在另一个文件里面

计数器值在 while 循环内的 if else 条件下仅递增一次