Writing a struct into a file but reading it incorrectly

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

struct Student
{
    int id;
    int grade;
};

struct Student john;

int main()
{

    john.id = 100;
    john.grade = 80;

    struct Student steve;

    fwrite(&john, sizeof(struct Student), 1, stdout);
    fread(&steve, sizeof(struct Student), 1, stdout);

    printf("\n%d %d \n", steve.id, steve.grade);

    return 0;
}

I am trying to write a struct into a file(in this case it is stdout), then I am trying to read it.

The values it prints are random, what could be the reason?

1 Answers

As already stated in the comments, you cannot read from stdout, however you could do it in a file that can be opened to read and write, you can even replace stdout with such file, for instance in UNIX uising unnamed pipes, chek C language. Read from stdout.

However you'd still need to reposition your file offset after you write so you can read from the beggining of the file, example:

int main()
{

    john.id = 100;
    john.grade = 80;

    FILE* f = fopen("test", "w+"); // check return value..

    struct Student steve;

    fwrite(&john, sizeof(struct Student), 1, f); // same here...

    fseek(f, 0, SEEK_SET); // <-- reset offset, (or lseek if you're using a file descritor)

    fread(&steve, sizeof(struct Student), 1, f); // and here

    printf("\n%d %d \n", steve.id, steve.grade);

    fclose(f);

}
Related