当文件名与其目录一起写入时,c 中的打开函数找不到文件
open function in c can't find a file when the file name is written with its directory
当我尝试打开当前目录中的文件时,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)
代码运行良好。为什么我每次写文件的目录,都找不到文件?
是因为你的工作目录没有名为的目录 child1
.
open("/child1/openthis.c", O_RDONLY)
should be
open("child1/openthis.c", O_RDONLY)
, and it works like this:
If your working directory is child1
, it will search for child1
folder inside the working directory. If found, it will search for openthis.c
inside child1/child1
, then opens it.
open("child1/openthis.c", O_RDONLY)
searches for "child1/child1/openthis.c"
open("openthis.c", O_RDONLY)
searches for "child1/openthis.c"
假设 child1
是您的工作目录,openthis.c
是其中唯一的文件,没有其他 folders/files。 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
当我尝试打开当前目录中的文件时,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)
代码运行良好。为什么我每次写文件的目录,都找不到文件?
是因为你的工作目录没有名为的目录 child1
.
open("/child1/openthis.c", O_RDONLY)
should beopen("child1/openthis.c", O_RDONLY)
, and it works like this:If your working directory is
child1
, it will search forchild1
folder inside the working directory. If found, it will search foropenthis.c
insidechild1/child1
, then opens it.
open("child1/openthis.c", O_RDONLY)
searches for"child1/child1/openthis.c"
open("openthis.c", O_RDONLY)
searches for"child1/openthis.c"
假设 child1
是您的工作目录,openthis.c
是其中唯一的文件,没有其他 folders/files。 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