0

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.

2
  • return 0 should be return, since it's a void function. Commented Nov 8, 2014 at 19:30
  • 1
    And read your compiler warnings. They point out all the problems in your code. Commented Nov 8, 2014 at 19:30

1 Answer 1

3

You need to change

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

to

 if ((bin = fopen("test.bin", "wb")) == NULL)
Sign up to request clarification or add additional context in comments.

2 Comments

You should explain why the original code doesn't work, i.e. how it's being grouped.
Because == has a higher predecence than =, bin is not set to the file pointer, but to either 0 or 1, the result of the == comparison. If the file was successfully opened, fopen() != NULL and so bin == 0 thus skipping the error report. However OP is then trying to call fwrite() with a file pointer of value 0 or NULL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.