me45
me45

Reputation: 1119

using fwrite() to write a struct to a file

I have the following program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 100

typedef struct {int key; char data[MAXLEN];} record;

main(int argc, char *argv[])
{
    int n, i;
    record x;
    FILE *fp;
    fp = fopen(argv[1], "w+");
    printf("How many records will be entered? \n");
    scanf("%d", &n);
    for (i=0; i<n; i++)
    {
        printf("Enter record: \n");
        scanf("%d", &x.key);
        scanf("%s", &x.data);
        fwrite(&x, sizeof(record), 1, fp);
    }
}

What I am doing is creating records from user input, and then storing these "records" into a file. However, when I use fwrite(), the file that is created has a lot of strange characters written in it, instead of simply having each record with its key and data. Can anyone tell me why it's writing all of these strange characters?

Upvotes: 6

Views: 9326

Answers (3)

shankar0015
shankar0015

Reputation: 11

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()

Upvotes: 1

Osiris
Osiris

Reputation: 4185

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.

Upvotes: 0

MJZ
MJZ

Reputation: 1082

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.

Upvotes: 4

Related Questions