Giulio Paoli
Giulio Paoli

Reputation: 87

lstat returning <0

Basically, this should be a simple piece of code that opens a directory stream and looks for symbolic links. Whenever a symbolic link is found, it should print ("Symbolic link found"); However, the lstat(dirp->d_name,&bufcall always returns a value < 0, and I don't know why. I created the two symbolic link opening the file folder, opening a terminal window inside the folder and running ln -s ciao.txt link1 and ln -s ciao2.txt link2 I know I should call closedir() later in my code, please don't care about this.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

void main (int argc, char* argv[])
{
    char buffer[100],dir[100];
    struct stat buf;
    int x;
    DIR *dp;
    struct dirent *dirp;
    if((dp=opendir(argv[1]))==NULL)
    {
        printf("\nError opening directory stream, now exiting...\n");
        exit(-1);
    }
    while((dirp=readdir(dp))!=NULL)
        {
            lstat(dirp->d_name,&buf);
            if(S_ISLNK(buf.st_mode))    
                printf("\n%s Is a symbolic link\n",dirp->d_name);
            else
                printf("\n%s Is not a symbolic link\n",dirp->d_name);



        }


}

Some help would be appreciated. Thanks.

Upvotes: 0

Views: 330

Answers (1)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

d_name is the file name in the directory, not a full path name. You must eather chdir into the directory you are looking at, or construct full path names for the files.

The simplest solution is to add this line just before your while loop:

chdir(argv[1]);

Upvotes: 1

Related Questions