Operating System - Linux
1752793 Members
5995 Online
108789 Solutions
New Discussion юеВ

How to found out if I'm reading a file/link/directory using stat

 
SOLVED
Go to solution
Roy Colica
Advisor

How to found out if I'm reading a file/link/directory using stat

I'm going to prepare some C-code in HP-UX 11.11 reading a directory and prepare a list of all links in it.
I open the dir with opendir, read it with readdir and I get the name of the entries.
How can I understand if they are links or directory or no-link files?
Can stat or lstat help me? I cannot understand how. Please help.
Roy

......
dir = opendir("/tmp")
lsdir=readdir(ifdir);
while ((lsdir = readdir(dir)) != NULL)
{
// how to know if a lsdir->d_name entry is a
// file, link or a directory?
}
closedir(ifdir);
..............
4 REPLIES 4
Muthukumar_5
Honored Contributor

Re: How to found out if I'm reading a file/link/directory using stat

dev_t st_dev; /* ID of device containing a */
/* directory entry for this file */

It gives file type. You can know the type of file.

hth.
Easy to suggest when don't know about the problem!
Stephen Keane
Honored Contributor
Solution

Re: How to found out if I'm reading a file/link/directory using stat

Use lstat() on the file. If you use stat() on a symbolic link it will return information on the file the link points to, not the link itself.

Then use S_ISDIR(), S_ISREG() or S_ISLNK() to determine if the file is a directory, regular file (not device file) or symbolic link.

e.g.

struct stat stat_info;
int rc;

rc = lstat(yourfile, &stat_info);

if (rc != 0)
{
// stat error
}

if (S_ISDIR(stat_info.st_mode))
{
// it's a directory
}
else if (S_ISLNK(stat_info.st_mode))
{
// it's a symbolic link
}
else if (S_ISREG(stat_info.st_mode))
{
// it's a regular file
}
else
{
// it's something else - FIFO, device file etc
}

Muthukumar_5
Honored Contributor

Re: How to found out if I'm reading a file/link/directory using stat

Use this c program.

http://www.metalshell.com/view/source/116/

with lstat using st_dev for mapping with macro's like, S_ISLNK()

hth.
Easy to suggest when don't know about the problem!
Roy Colica
Advisor

Re: How to found out if I'm reading a file/link/directory using stat

Thanks to the forum...