I wrote my own find() function. When I do:
./myown $HOME/Documents test.txt
I get:
/Users/CJ/Documents/test/test.txt
/Users/CJ/Documents/test/test1/test.txt
/Users/CJ/Documents/test/test2/test.txt
However when I do:
./myown $HOME test.txt
I get:
getcwd error
My code for getcwd is here and it is in a helper function:
findit(*directory, *pattern){
...
if(getcwd(cwd, 2048+1) == NULL){
fprintf(stderr, "getcwd error\n");
exit(1);
}
...
}
How can I solve this issue?
EDIT: closedir()
solve this issue but there is another issue now. Result is the same when I do : ./myown $HOME/Documents test.txt
but when I do the other way I get : stat error
`
struct stat mode;
if(stat(entry->d_name, &mode) == -1){
fprintf(stderr, "stat error\n");
continue;
}`
I didn't use stat error anywhere else in the code.
This can be helpful too, this is how I used open
DIR *dir
dir = opendir(".");
The error is in readdir().
One suggested step in debugging was:
Since
getcwd()
setserrno
when it fails, you should probably reporterrno
, maybe withperror("getcwd")
. Although I'm not keen onperror()
, it is probably simplest here.
It turns out that the error set was 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.
And, when requested, I elaborated on that with:
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 thegetcwd()
fails. It probably isn't immediate; your program has probably done some processing before that failure.
The OP observed:
I just saw that I haven't used
fclose
; give me a second and I will check it if that's it.
Making sure you've used fclose()
and closedir()
— and plain close()
if you've used any file descriptors by calling open()
directly — should help. If, however, the call to getcwd()
is the very first thing your code is doing, it won't be because you've opened many files (you haven't).
If there are still problems after files have been closed, then you need to take a step back and review the larger context.
For example: