簡體   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