1
votes

I am writing a C program that converts a text file into a binary file and vice versa. The first question I have is about opening a file in "w" mode. Is there any need to have a check that the output file is opened correctly?

FILE *output;
output = fopen("output.bin", "w");
if(output == NULL)
    { printf("Error opening output file\n");}

Basically my question is whether or not output would ever actually == NULL. Because if there was a problem opening the output wouldn't it just create a new file named "output.bin"?

Also my other question is how characters are actually saved in a binary file. I know I'm supposed to save each character as an unsigned char so it can have values between 0 and 255 and then I should write that char to the output file. The actual logical path of how that happens is not making sense if anyone can help me or point me in the right direction I would appreciate it!

1
What do you mean exactly by "converts a text file into a binary file and vice versa"? - e0k
"Is there any need to have a check that the output file is opened correctly". Yes absolutely you need to check the return value. At minimum it is good practice. And certainly the open can fail for many reasons. For example, no permissions to create files in the current directory. Or file already exists but is not writeable. - kaylum
' trying to understand how binary files are stored and represented' - oh, believe me, that's real easy:) It's 'text files' that are handled anomalously. - Martin James
I believe you're supposed to have one question per question. - user253751
You should use "wb" instead of "w" when trying to create a binary file, in case this code runs on Windows systems. - user5885662

1 Answers

3
votes

Yes, opening a file in write mode might still fail. Here's a bunch of possible reasons, but certainly not the only ones:

  • You don't have permission to create or change the file.
  • The file is read-only, or the directory it would be in is read-only.
  • The file would be inside another file. (test/foo if test is a file and not a directory)
  • The filesystem is out of space or inodes (on filesystems that have a fixed number of inodes)
  • The user has hit their disk space quota.
  • The file would be on another computer, and the network is down.
  • The filename is invalid - such as C:/???*\\\\foo on windows.
  • The filename is too long.