Search code examples
cfileiobinaryfwrite

Wrong output when writing to a file in binary format


Im trying to write some user input to a file in binary format. When I look at the file im expecting to see only 0 and 1's, but output to the file is printed in normal text:

    FILE *f;
    char array[8];
    f = fopen("numbers.bin", "ab+");
    if(f==NULL){
        printf("Could not open file!\n");
        system("pause");
        exit(1);
        }

     for(i=0;i<numberOfInputs;i++){
         printf("\nEnter number nr %i:", i+1);
         gets(array); //get the input and place it in array
         strcat(array, "\n"); // add a newline to the input
         fwrite(array,sizeof(char),1,f); //write output to the file
}

Is anyone able to spot what im doing wrong here?


Solution

  • since you read the input as string (gets), this is how the data is written later. You need to use scanf to read the numbers.

    int num;
    scanf("%d", &num);
    fwrite(&num, sizeof(int), 1, f);