1

I am reading and writing a struct to/from a random access file. File pointer is defined in the main function and passed to other functions. I tried to put fflush everywhere that I can yet I still get this error. I don't know what I am missing.

typedef struct seatdata
{
    int seat_num;
    char name[15];
    char surname[15];
    char gender;
}Seatdata;

...

void newReservation( FILE* data )
{
    Seatdata buffer;
    int seat_number;

    printf( "Enter seat number to be reserved: " );
    scanf( "%d", &seat_number );

    fseek( data, (seat_number-1)*sizeof(Seatdata), SEEK_SET );

    fread( &buffer, sizeof(Seatdata), 1, data );
    fflush( data );

    if ( buffer.seat_num != 0 )
    {
        printf( "This seat has already been reserved." );
        return;
    }

    printf("Enter name surname and gender: " );

    scanf("%s %s %c", buffer.name, buffer.surname, &buffer.gender );


    fwrite( &buffer, sizeof(Seatdata), 1, data );
    fflush( data );
} 

...

int main ( void )
{
    FILE* data = NULL;
    data = fopen( "bus.dat", "rb+" );
    if ( data == NULL ) { return -1; }

    newReservation( data );

    return 0;
}

Error comes at the fwrite part. And apparently I am required to pass the FILE* to functions. ( This is an assignment )

aulven
  • 521
  • 3
  • 14
  • It is unclear why you are doing `fflush( data );` after `fread( &buffer, sizeof(Seatdata), 1, data );` – Weather Vane Apr 16 '20 at 19:40
  • *When the "r+", "w+", or "a+" access type is specified, both reading and writing are enabled (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind. When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function.* – Weather Vane Apr 16 '20 at 19:42
  • 1
    What I asked, is what is the point of a flush after a read? What are you flushing? Flushing an input stream is *undefined behaviour*. – Weather Vane Apr 16 '20 at 19:43
  • I called the same fseek line before calling the fwrite. It now works. Thanks. (I was trying to find what the issue was, so I tried to put fflush everywhere that made sense to me.) – aulven Apr 16 '20 at 19:45
  • Also, what I though fflush were doing was act as if file is closed and reopened. I guess that was not the case. – aulven Apr 16 '20 at 19:48
  • ***7.21.5.2** 2. If stream points to an output stream or an update stream **in which the most recent operation was not input**, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is **undefined**.* (my bolding) – Weather Vane Apr 16 '20 at 19:53

0 Answers0