-6

I'm trying to write the following structure into a file and read it back. The issue I am having is I do not know how to use the fread and fwrite functions properly!

struct M{
    char album[50];
    char artist;
    char category;
    float price;
    int   stock;
};
struct M s[10];

I tried some code I found here, but the output from the file has strange characters. I guess it isn't working properly.

Retired Ninja
  • 4,785
  • 3
  • 25
  • 35
user3219446
  • 117
  • 1
  • 11
  • 4
    Voting -1 for lack of research effort. There's umpteen tutorials around on using these functions both for single pieces of data and for using them to serialize structures like this. – enhzflep Aug 01 '14 at 00:07
  • 3
    A duplicate question means your problem is similar enough to that problem that the solutions provided are the same. It has nothing to do with who asked the question. – Retired Ninja Aug 01 '14 at 02:32

1 Answers1

2

You probably want artist and category to be array of char too.

struct M{
    char album[50];
    char artist[50];
    char category[50];
    float price;
    int   stock;
};
struct M s[10];

then you can use fwrite this way

fwrite(s, sizeof(s), 1, file);

or equivalently

fwrite(s, sizeof(M), 10, file);

You can read in the same manner:

fread(s, sizeof(s), 1, file);

or equivalently

fread(s, sizeof(M), 10, file);

but you will need to open the file before

FILE * file = fopen("thisFile", "bw"); // binary write mode

or

FILE * file = fopen("thisFile", "br"); // binary read mode

Close the file when you're done.

fclose(file);

And check that file is not == NULL after fopen.

However, you will soon want to read/write a file with a size unknown at compile time. So you will want dynamic memory allocation based on the file size. But that's for another question ;)

All the info you need can be found there: http://www.cplusplus.com/reference/cstdio/fopen/

ThreeStarProgrammer57
  • 2,906
  • 2
  • 16
  • 24