繁体   English   中英

在 C 中使用 fread 和 fwrite 阻止读写

[英]Block reading and writing using fread and fwrite in C

我正在尝试从用户读取员工信息并使用 fwrite() 函数将其输入到文件中,然后我想使用 fread() 在屏幕上打印数据内容以从文件中读取然后打印它。 当我在程序中时,这个过程工作得非常好,但在程序退出并访问存储信息的文件后,我看到了不可读的字符,但在程序中,它们被打印为普通的英文字符和数字。 这是我的代码:

#include<stdio.h>

struct emp{
    int id;
    char name[30];
    double salary;
}S;

void main(){
    char fname[60];
    printf("Enter file name: ");
    scanf("%s", fname);

    FILE *fptr = fopen(fname, "a+");        // open file in append + mode, create if not found.

    if(fptr == NULL){
        printf("Some error occured !\n");
        return;
    }

    int i, size;
    printf("Enter the number of employees whose information is needed to be added to the file: ");
    scanf("%d", &size);

    // writing

    for(i = 0 ; i < size ; i++){
        printf("Employee %d:\n", i+1);
        printf("Enter id: ");
        scanf("%d", &S.id);

        printf("Enter name: ");
        while(getchar() != '\n');   // clear buffer
        scanf("%s", S.name);

        printf("Enter salary: ");
        scanf("%lf", &S.salary);

        fwrite(&S, sizeof(struct emp), 1, fptr);
        printf("----------------------------------------\n");
    }

    rewind(fptr);           // move pointer to first record in file

    // reading
    printf("File contents: \n");

    printf("ID\t\tNAME\t\tSALARY\n");

    while(fread(&S, sizeof(struct emp), 1, fptr) != 0){
        printf("%d\t\t%s\t\t%lf\n", S.id, S.name, S.salary);    
    }
}

这是我试图解释的图片。 在此处输入图片说明

您正在将结构写入文件,而不是单独打印其内容。 当你读回它时它会工作,但是当你打开文件时,它根本不知道它是什么(你的结构中有intchar*double

如果你想在文件上可视化它,你需要单独打印结构的每个术语,并以相同的方式读回来,以便在屏幕上看到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM