简体   繁体   中英

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

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.

我认为代替rb应该是wb,因为你正在写文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM