2
#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?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
user9679818
  • 103
  • 8
  • 1
    You do know that `stdout` is the ***output*** file handle of the terminal or console? I suggest you start by adding error checking to all functions that can return a success/failure, like `fwrite` and `fread`. – Some programmer dude Apr 04 '21 at 12:55
  • @Someprogrammerdude yes, but does that make a difference ? Aren't they all treated as files ? – user9679818 Apr 04 '21 at 12:56
  • File can be read-only, write-only, or read-write. `stdout` is write-only. This is basically what the second argument to [`fopen`](https://en.cppreference.com/w/c/io/fopen) is for. – Some programmer dude Apr 04 '21 at 12:58
  • What do you mean by "random"? I would expect the write to successfully write the values, but they won't display nicely on your screen. The `fread` I would expect to fail. – William Pursell Apr 04 '21 at 13:02
  • Perhaps think about it like this: `stdout` is the *console* or *terminal*. Where would data you write to `stdout` actually be stored? It's just written into the console or terminal. – Some programmer dude Apr 04 '21 at 13:03
  • @WilliamPursell Okey the first part is always dP which corresponds to 100 and 80.But the other two values are random. – user9679818 Apr 04 '21 at 13:13
  • always check for return types specially when doing IO – asio_guy Apr 04 '21 at 13:38

1 Answers1

4

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

}
anastaciu
  • 23,467
  • 7
  • 28
  • 53