Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'fopen' return a NULL pointer?

Tags:

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; } 
like image 556
k787 Avatar asked May 13 '11 05:05

k787


1 Answers

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.

like image 81
Gabe Avatar answered Sep 22 '22 16:09

Gabe