Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c - How do you determine using stat() whether a file is a symbolic link?

I basically have to write a clone of the UNIX ls command for a class, and I've got almost everything working. One thing I can't seem to figure out how to do is check whether a file is a symbolic link or not. From the man page for stat(), I see that there is a mode_t value defined, S_IFLNK.

This is how I'm trying to check whether a file is a sym-link, with no luck (note, stbuf is the buffer that stat() returned the inode data into):

switch(stbuf.st_mode & S_IFMT){
    case S_IFLNK:
        printf("this is a link
");
        break;
    case S_IFREG:
        printf("this is not a link
");
        break;
}

My code ALWAYS prints this is not a link even if it is, and I know for a fact that the said file is a symbolic link since the actual ls command says so, plus I created the sym-link...

Can anyone spot what I may be doing wrong? Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't.

You need to use lstat() to stat the link itself, plain stat() will follow the link, and thus never "see" the link itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...