Why does 'fopen' return a NULL pointer?

不想你离开。 提交于 2019-11-26 07:46:10

问题


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;
}

回答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.




回答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.




回答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.




回答4:


Is fopen for write return NULL in the first run?

I noticed that in the while you keep open files for write but not closing them.

Try to add fclose(outFile) after fwrite:

outFile =  fopen ( current_file_name , "wb" );    
fwrite(output, sizeof( char ), bytes_read, outFile); 
fclose(outFile)

It is possible you open more files than your OS allows.




回答5:


As Gabe said your problem is newline in filename which is illegal in Windows.

But why don't you just use split from GNU Core Utilities. Installed by default on Unices/Linux, can be downloaded for Windows from GnuWin32 project.

split --suffix-length=4 --numeric-suffixes --bytes=1M - part < filename



回答6:


In Unix, for fopen(), there is no reason to prepend ./ to a filename passed to fopen().




回答7:


In my case, i was reading the same file all over again in a while loop and forgot to close it.

I used a function for reading the file and finding a match and the function had a return; statement that terminated the function before doing fclose(fp) :D




回答8:


The path given for the file is checked from wherever the executable is present. In my case I was opening the text file in c file when both were present at the same place. It was continuously giving the error of file not found. Placed the file in the folder of executable and it started working.




回答9:


In my case, it was because I was trying to create the file in a directory that does NOT exist.



来源:https://stackoverflow.com/questions/5987626/why-does-fopen-return-a-null-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!