0

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?

3
  • 1
    You expect "only 0s and 1s"?! What are you trying to do? Should the user enter numbers (integers, to be more precise) and you want to append these in (OS-dependent) binary format? Or do you want to append the strings with appended newline characters as-is? Commented Mar 9, 2012 at 14:27
  • Don't use gets. If there is a line bigger than 8 charcaters in your file, you have a buffer overflow. Commented Mar 9, 2012 at 14:28
  • For the buffer overflow reason, gets() was recently removed from the C language, when the current version of the standard (C11) was released. Programs using gets() will not compile on future C compilers. Commented Mar 9, 2012 at 14:52

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Edited the code using your hints, where im looping thru the array and read each element with scanf, and write that to the file. Im getting non-readable output, so it might be working as expected. I'll accept this as as answered when I've verified the output :)
1

You're only writing one char.

Try...

fwrite(array,strlen(array),1,f);

These docs show that the second parameter is the size of the element to write, and the third is the number of items. You could put these two around the other way, or put sizeof(char) instead of 1 (this is always one).

Beware that you'll have an issue here if the user inputs a string longer than 6 chars - since the newline and null terminator also take up memory.

1 Comment

The above code worked, but still prints in "normal" text when im viewing the file with notepad

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.