Search code examples
cfilebinaryfwrite

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.


Solution

  • You need to change

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

    to

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