Quik19
Quik19

Reputation: 362

Even opening the file with "rb+" it isn't writing in binary

I have this struct declared:

typedef struct {
char *TITLE;
char *AUTHOR;
char *PUBLISHER;
int YEAR;
char *LANGUAGE;
int PAGES;
float PRICE;
} Book;  

And I'm trying to use the function below to write in binary a Book in a empty file called "BD_Books.bin":

void InsertBook(Book *L){
FILE *arq = fopen("BD_books.bin", "rb+");
if(arq == NULL){
    printf("ERROR WHILE OPENING FILE!!");
    return;
}
int regFile = -1;

fseek(arq, 0, SEEK_SET); //setting "pointer" to the beggining of file
fscanf(arq, "%d", &regFile); //reading first integer from file
if(regFile == -1){ //if the file is empty
        fwrite(L->TITLE, sizeof(char), strlen(L->TITLE), arq);
        fwrite(L->AUTHOR, sizeof(char), strlen(L->AUTHOR), arq);
        fwrite(L->PUBLISHER, sizeof(char), strlen(L->PUBLISHER), arq);
        fprintf(arq, "%d", L->YEAR);
        fwrite(L->LANGUAGE, sizeof(char), strlen(L->LANGUAGE), arq);
        fprintf(arq, "%d", L->PAGES);
        fprintf(arq, "%f", L->PRICE);
        return;
}  

I can write all the data the way I want, but the problem is that I have to write it in binary format, but the function os writing as a text.
Isn't fopen("BD_books.bin", "rb+"); enough to tell fwrite() to write all the data as binary, since I'm opening the file with the "rb+" argument??

Upvotes: 1

Views: 583

Answers (2)

Sajal Jain
Sajal Jain

Reputation: 273

I think instead of rb it should be wb, since you are writing to the file.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Because you need to use fwrite() and not fprintf(), fprintf() writes strings to the file, whose byte representation is the same as their string representation.

Try chaging

fprintf(arq, "%d", L->YEAR);

with

fwrite(&L->YEAR, sizeof(L->YEAR), 1, arq);

And also, sizeof(char) is guaranteed to be 1, so using it adds unnecesary ugliness to the code, making it harder to read.

Upvotes: 2

Related Questions