using fwrite() to write a struct to a file

后端 未结 3 1500
深忆病人
深忆病人 2021-01-18 08:54

I have the following program:

#include 
#include 
#include 

#define MAXLEN 100

typedef struct {int key; char         


        
相关标签:
3条回答
  • 2021-01-18 09:31

    It's storing the data as binary records, not plain text.

    You won't be able to view it using notepad.

    To view the records, you'll have to write another program that reads records from the file into the same structure.

    0 讨论(0)
  • 2021-01-18 09:48

    Several reasons:

    1. When you use scanf, it translates a human readable form (%d) into something the computer uses directly (int). You then write out the computer-readable form into a file. Now, when you view the file, you are NOT using the inverse computer-to-human-readable form but something much lower-level. This will give you something that looks wrong.
    2. You are writing out the entire x.data even though you may have read partial data into it (say, reading a string that's length 10). The remainder of the x.data is "uninitialized" and contains whatever was left in memory when main() was called.
    0 讨论(0)
  • 2021-01-18 09:49

    I have also had same kind of problem while reading BIOS parameter block structure from a floppy disk image. I resolved it by using #pragma pack(1) directive. Sample code is below:

    #pragma pack(1)
    struct bpb
    {
        unsigned char jmpinstruction[3];
        unsigned char oem[8];
        short bytespersector;
        ....
    };
    #pragma pack()
    
    0 讨论(0)
提交回复
热议问题