简体   繁体   中英

Why fwrite doesn't work for binary files in C?

I want to write some data into a binary file, using C language. Apparently, the function fwrite doesn't seem to work properly. This is the code:

typedef struct tw {
    char name[40];
    char tweet[150];
    int rt, like;
} Twitter;

void createFile() {
    FILE *bin;
    Twitter user;
    if (bin = fopen("test.bin", "wb") == NULL) {
        printf("Error");
        return 0;
    }
    strcpy(user.name, "name");
    strcpy(user.tweet, "this is a tweet");
    user.rt=5;
    user.like=10;

    fwrite(&user, sizeof(Twitter), 1, bin);

    fclose(bin);

}

The fwrite function doesn't write anything into the file, and I've looked for mistakes in the code, but I couldn't find any. Also, when I tried to use the function to write into a txt file, it worked correctly.

You need to change

if (bin = fopen("test.bin", "wb") == NULL)

to

 if ((bin = fopen("test.bin", "wb")) == NULL)

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