fwrite() not working to write integer in binary file

后端 未结 4 999
暖寄归人
暖寄归人 2021-01-16 23:25

Can someone tell my why won\'t this function work? I just can\'t get it...

void writeRegister(FILE *arq, Book *L){ //writes in actual file position
  char          


        
4条回答
  •  悲哀的现实
    2021-01-17 00:20

    The signature of fwrite is

    std::size_t fwrite( const void* buffer, std::size_t size, std::size_t count, std::FILE* stream );
    

    The first argument to the function needs to be a pointer. I am surprised you didn't get compiler errors with the following lines.

    fwrite(L->YEAR, sizeof(int), 1, arq);
    fwrite(L->PAGES, sizeof(int), 1, arq);
    fwrite(L->PRICE, sizeof(float), 1, arq);
    

    They need to be

    fwrite(&(L->YEAR), sizeof(int), 1, arq);
    fwrite(&(L->PAGES), sizeof(int), 1, arq);
    fwrite(&(L->PRICE), sizeof(float), 1, arq);
    

    Also, it is a good practice to check the return values of all IO functions to make sure that they work as you expect them to.

    if ( fwrite(&(L->YEAR), sizeof(int), 1, arq) != 1 )
    {
       // Deal with the error condition.
    }
    

提交回复
热议问题