Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c-can'中的open函数;当文件名与目录一起写入时,无法找到文件_C_File_Directory - Fatal编程技术网

c-can'中的open函数;当文件名与目录一起写入时,无法找到文件

c-can'中的open函数;当文件名与目录一起写入时,无法找到文件,c,file,directory,C,File,Directory,当我尝试在当前目录中打开一个文件时,open函数可以正常工作,但是如果我在open函数中以文件名作为参数提到文件的目录,则会发生文件未找到错误。另外,当我试图用open函数打开另一个目录中的文件时,终端打印出没有这样的文件或目录。我找不到写入文件目录的问题所在 现在我在'child1'目录下工作,我想打开'openthis.c'文件。这是我想要执行的代码 #include<fcntl.h> #include<stdlib.h> #include<sys/stat.h

当我尝试在当前目录中打开一个文件时,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("/child1/openthis.c", O_RDONLY)

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

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

open(“/child1/openthis.c”,O_RDONLY)
应该是
open(“child1/openthis.c”,ordonly)
,其工作原理如下:

child1
   L child1
       L openthis.c
child1
   L openthis.c
       
  
如果您的工作目录是
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”,ordonly)
如果目录树如下所示,则可以正常工作:

child1
   L child1
       L openthis.c
child1
   L openthis.c
       
  
open(“openthis.c”,O_RDONLY)
之所以有效,是因为
openthis.c
位于您的工作目录中

您的目录可能如下所示:

child1
   L child1
       L openthis.c
child1
   L openthis.c
       
  

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