Why does 'fopen' return a NULL pointer?

倖福魔咒の 提交于 2019-11-26 20:57:08
Gabe

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.

JaredPar

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.

Sohail xIN3N

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.

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.

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
Vinoj John Hosan

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

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

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.

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