Why does 'fopen' return a NULL pointer?
I'm working on a simple file splitter/merger program in the C programming language. The problem is, for some reason fopen returns NULL, and because of that, my program is crashing at the fwrite statement. How do I fix this?
Here is the C file:
int SplitFile(char* filename, char* output, size_t size)
{
char current_file_name[256];
int file_count = 0, i = 0;
FILE *file = fopen( filename, "rb" );
printf("split %s into chunks of %d named\n", filename, size);
if (!file)
return E_BAD_SOURCE;
else
{
output = (char *) malloc(size * sizeof(char));
if (output == NULL)
return E_NO_MEMORY;
else
{
int bytes_read = 0;
FILE *outFile;
do
{
bytes_read = fread(output, sizeof(char), size, file );
sprintf(current_file_name, "%s%04lu\n", "part", file_count++);
outFile = fopen (current_file_name, "wb" ); // THIS RETURNS NULL
fwrite(output, sizeof(char), bytes_read, outFile); //CRASHES ON THIS LINE
}
while ( bytes_read > 0 )
;
//fclose(outFile);
}
}
fclose(file);
printf("...\n");
return 0;
}
Solution 1:
The proper thing to do is check errno
when fopen
returns NULL
.
I'm going to guess that your problem is that you're trying to write to a filesystem that doesn't allow \n
in filenames, but it could be a permissions issue as well.
Solution 2:
There are many reasons fopen
can return NULL
including (but certainly not limited to):
- The file doesn't exist
- The file is opened in a mode that doesn't allow other accesses
- The network is down
- The file exists, but you don't have permissions
- A file exists with the name you gave, but the current directory of the process is not what you expected so the relative pathname fails to find and open the file.
The way to find out which is responsible is to dig into the errno
code.
However just because you resolve this particular error doesn't mean you can assume fopen
will never return NULL
. When dealing with I/O operations your code simply has to expect failure. It's not possible to predict the success of I/O operations, and they can always fail.
Solution 3:
It means that the file might not exist or some permission error occurred while accessing a file such as "Read-Only" or "Write-Protected", so in those cases fopen will return 0 (a NULL pointer). On success it will return a file pointer as a handler.
fp=fopen("c:\\ABC.txt", "r");
cannot be the same as fp=fopen("c:\\abc.txt", "r");
.
Use //
instead of \\
in a Linux environment.
P.S.: In Linux and Unix-like operating systems file names are case-sensitive.