Search code examples
cstringfile-iobinaryfilesfwrite

Trying to store a string in a file using binary mode in C


I am trying to store a simple string in a file opened in wb mode as shown in code below. Now from what i understand, the content of string should be stored as 0s and 1s as it was opened in binary mode but when i opened the file manually in Notepad, I was able to see the exact string stored in the file and not some binary data. Just for curiosity I tried to read this binary file in text mode. Again the string was perfectly shown on output without any random characters. The below code explains my point :

#include<stdio.h>
int main()
{
    char str[]="Testing 123";
    FILE *fp;
    fp = fopen("test.bin","wb");
    fwrite(str,sizeof(str),1,fp);
    fclose(fp);
    return 0;
} 

So i have three doubts out of this:

  1. Why on seeing the file in Notepad, it is not showing some random characters but the exact string ?
  2. Can we read a file in text mode which was written in binary mode and vice versa ?
  3. Not exactly related to above question but can we use functions like fgetc, fputc, fgets, fputs, fprintf, fscanf to work with binary mode and functions like fread, fwrite to work with text mode ?

Edit: Forgot to mention that i am working on Windows platform.


Solution

    • In binary mode, file API does not modify the data but just passes it along directly.
    • In text mode, some systems transform the data. For example Windows changes \n to \r\n in text mode.
    • On Linux there is no difference between binary vs text modes.
    • Notepad will print whatever is in the file so even if you write 100% binary data there is a chance that you'll see some readable characters.