fopen() 返回空指针,但文件肯定存在 [英] fopen() returning a NULL pointer, but the file definitely exists

查看:35
本文介绍了fopen() 返回空指针,但文件肯定存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

FILE *txt_file = fopen("data.txt", "r");
if (txt_file == NULL) {
    perror("Can't open file");
} 

返回的错误信息为:

无法打开文件:没有那个文件或目录

Can't open file: No such file or directory

文件data.txt"肯定存在于工作目录中(它存在于包含我的 .c 和 .h 文件的目录中),那么为什么 fopen() 返回一个 NULL 指针?

The file 'data.txt' definitely exists in the working directory (it exists in the directory that contains my .c and .h files), so why is fopen() is returning a NULL pointer?

推荐答案

有没有可能文件名不是真正的data.txt"?

Is it possible that the filename is not really "data.txt"?

在 Unix 上,文件名实际上是字节字符串而不是字符串,并且可以创建名称中带有退格等控件的文件.过去我曾见过这样的情况,即复制粘贴到终端中会导致文件名称看起来很普通,但尝试打开出现在目录列表中的文件名会导致错误.

On Unix, filenames are really byte strings not character strings, and it is possible to create files with controls such as backspace in their names. I have seen cases in the past in which copy-pasting into terminals resulted in files with ordinary-looking names, but trying to open the filename that appears in a directory listing results in an error.

一种确定文件名是否与您认为的一样的方法:

One way to tell for sure that the filenames really are what you think they are:

$ python
>>> import os
>>> os.listdir('.')

这篇关于fopen() 返回空指针,但文件肯定存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆