Reputation: 1
I use lstat
to take a file`s characteristics, but it doesn't appear to work, it returns -1 and the error -No such file or directory-.
I try the path in the shell, typing :
:~$ ls /home/mypc/Desktop/file.c
/home/mypc/Desktop/file.c
So this path obviously works with ls
, but not with lstat
! It is very weird.
This is the line in which I call lstat
:
int i=lstat(path, &buff );
path
is a char[]
and buff
is a struct stat
object.
Please if you have any ideas...
Upvotes: 0
Views: 5173
Reputation: 87
From the man page of fgets
:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer[...].
So this is your situation.
path\n\0
^^^^ ^ ^
1234 5 6
Remmber this! Hope it helped.
Upvotes: 1
Reputation: 1
Thank you for your answer. It is right that I use fgets to read a line from a pipe that gives me the paths. The problem is not that the files is unreacheable for sure,because I checked this. the problem is the path itself.I do:
while ( (fgets ( path, 512, f ) )) {//path name is f.e.: ./.local/share/Trash/files/myFile.c
struct stat buff;
//here I have the path and I give it in lstat
if(lstat(&path[1], &buff )==0){ //I give path[1] and not path[0] to avoid the dot in the begining
}
}
the error must be the pathname.
Upvotes: 0
Reputation: 2232
From fgets manual page: If a newline is read, it is stored into the buffer.
So you are trying to lstat /path/yourfile.c\n
. Obviously you file name is yourfile.c
and not yourfile.c\n
.
more explanations added
Your "path file" is something like /path/to/yourfile.c\n/other/path/to/otherfile.txt\n
. The file "uses" \n
(new line) characters to separate the different entries in the file.
When you read it using fgets
, the path
variable is filled, each time, with a full line read from the "path file" including the ending \n
character. So if you look inside your program memory, you'll discover that path
looks like /path/to/yourfile.c\n\0somegarbage
(after the first call to fgets).
Now, you have to get rid of the trailing \n
, just before the \0
that identifies the end of the string.
As you wrote in one of the comments,you can use memset
to do this but, IMHO, there are easier ways.
Upvotes: 1
Reputation: 4444
First and foremost, look at the error value. The path may exist, but be otherwise reachable.
Upvotes: 0
Reputation: 29655
This is correct behavior. Your path doesn't exist.
From the documentation:
RETURN VALUES Upon successful completion a value of 0 is returned. Otherwise, a value of -1 is returned and errno is set to indicate the error.
As @Noufal states, you can try printing the path. It may be that your path has a \n
appended to it; this is likely if you read it with fgets
.
Upvotes: 4