gpt4 book ai didi

c - $HOME 时 getcwd 错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:03 24 4
gpt4 key购买 nike

我编写了自己的 find() 函数。当我这样做时:

./myown $HOME/Documents test.txt

我得到:

/Users/CJ/Documents/test/test.txt
/Users/CJ/Documents/test/test1/test.txt
/Users/CJ/Documents/test/test2/test.txt

但是当我这样做的时候:

./myown $HOME test.txt

我得到:

getcwd error

我的 getcwd 代码在这里,它在辅助函数中:

findit(*directory, *pattern){
...
if(getcwd(cwd, 2048+1) == NULL){
fprintf(stderr, "getcwd error\n");
exit(1);
}
...
}

我该如何解决这个问题?

编辑:closedir() 解决了这个问题,但现在还有另一个问题。当我这样做时,结果是一样的:./myown $HOME/Documents test.txt 但是当我以另一种方式进行时,我得到:stat error

` 
struct stat mode;
if(stat(entry->d_name, &mode) == -1){
fprintf(stderr, "stat error\n");
continue;
}`

我没有在代码的其他任何地方使用 stat error。

这也很有用,这就是我使用 open 的方式

DIR *目录
dir = opendir(".");

错误在 readdir() 中。

最佳答案

一个建议的调试步骤是:

Since getcwd() sets errno when it fails, you should probably report errno, maybe with perror("getcwd"). Although I'm not keen on perror(), it is probably simplest here.

原来设置的错误是EMFILE Too many open files.

So, now you know what the trouble is. The getcwd() is failing because you have opened a lot of files and not closed enough of them, and it needs some available file descriptors but you've not left it any that it can use.

并且,应要求,我详细说明了这一点:

You've opened files and/or directories (opening a directory with opendir() usually uses a file descriptor), and you've not closed them. Consequently, the system won't allow you to open any more files — and the getcwd() fails. It probably isn't immediate; your program has probably done some processing before that failure.

OP 观察到:

I just saw that I haven't used fclose; give me a second and I will check it if that's it.

确保您使用了 fclose()closedir() — 如果您使用了任何文件,则使用普通的 close()通过直接调用 open() 描述符 — 应该会有所帮助。但是,如果对 getcwd() 的调用是您的代码所做的第一件事,那不会是因为您打开了很多文件(您还没有打开)。

如果关闭文件后问题仍然存在,那么您需要退后一步,回顾更大的上下文。

例如:

关于c - $HOME 时 getcwd 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51110046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com