【问题标题】:open function in c can't find a file when the file name is written with its directory当文件名与其目录一起写入时,c中的open函数找不到文件
【发布时间】:2015-05-16 08:35:04
【问题描述】:

当我尝试打开当前目录中的文件时,open 函数工作正常,但是如果我在 open 函数中将文件的目录及其名称作为参数提及,则会发生找不到文件的错误。另外,当我尝试使用 open 函数打开另一个目录中的文件时,终端会打印出没有这样的文件或目录。我找不到写入文件目录的问题。

现在我在“child1”目录中工作,我想打开“openthis.c”文件。这是我要执行的代码。

#include<fcntl.h>
#include<stdlib.h>
#include<sys/stat.h>
int main(){
int fd;
if((fd = open("/child1/openthis.c", O_RDONLY) < 0){
perror("open");
exit(1);}
return 0;
}

这不起作用,但如果我写

open("openthis.c", O_RDONLY)

而不是

open("/child1/openthis.c", O_RDONLY)

代码运行良好。为什么每次写文件的目录,都找不到文件?

【问题讨论】:

  • ls -l /child1/openthis.c 说什么?
  • 你确定你的文件夹在你机器的根目录下吗?
  • 那么你没有一个名为/child1/openthis.c的文件。故事结束。
  • 是的。您需要提供文件的实际路径。
  • 请出示您的实际代码。由于括号不平衡,您问题中的代码无法编译。

标签: c file directory


【解决方案1】:

这是因为你的工作目录没有名为child1的目录。

open("/child1/openthis.c", O_RDONLY) 应该是 open("child1/openthis.c", O_RDONLY),它的工作原理是这样的:

如果您的工作目录是child1,它将在工作目录中搜索child1 文件夹。如果找到,它将在child1/child1 中搜索openthis.c,然后打开它。

open("child1/openthis.c", O_RDONLY) 搜索 "child1/child1/openthis.c" open("openthis.c", O_RDONLY) 搜索 "child1/openthis.c"

假设child1 是您的工作目录,openthis.c 是其中唯一的文件,没有其他文件夹/文件。 child1/child1/openthis.c 永远不会存在,除非您在工作目录(即 child1)内创建一个名为 child1 的新文件夹并在其中添加 openthis.c

您永远无法访问不存在的文件。

如果你的目录树是这样的,open("child1/openthis.c", O_RDONLY) 可以正常工作:

child1
   L child1
       L openthis.c

open("openthis.c", O_RDONLY) 有效,因为openthis.c 位于您的工作目录中。

你的目录可能是这样的:

child1
   L openthis.c
       
  

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2018-05-25
    • 1970-01-01
    • 2021-03-28
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多