简体   繁体   中英

Block reading and writing using fread and fwrite in C

I am trying to read employee information from the user and enter it into a file using fwrite() function and later i want to print the data contents on the screen using fread() to read from file and then print it. When i am inside the program, this process is working absolutely fine but after program is exited and i access the file where the information has been stored, i see unreadable characters but in the program they are printed as normal english characters and digits. Here is my code:

#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);    
    }
}

Here is the picture of what i am trying to expalin. 在此处输入图片说明

You are writing to the file the struct and not printing its contents separately. It works when you read it back, but when you open the file, it simply doesn't know what it is (you have int and char* and double in your struct.

If you want to visualize it on the file, you need to print each term of the struct individually, and read it back the same way, in order to see it on screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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