3

I am working on a program in C on a linux machine that displays the file type of a file presented as an argument to the program. The program needs to determine if a file is any one of the following: directory, device, (regular) file, link, socket, or fifo. I am not exactly sure how to determine file type.

Here is my code thus far (not much):

int main(int argc, char **argv) { if( argc == 1 ) /* default: current directory */ puts("Directory"); else while( --argc > 0 ) determine_ftype(*++argv); return 0; } 

Thanks!

1 Answer 1

13

Use the POSIX stat function and read the st_mode field of the structure struct stat returned by the function.

stat function:

http://pubs.opengroup.org/onlinepubs/7908799/xsh/stat.html

The structure struct stat type:

http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html

For glibc, you can also read the section 14.9.3 Testing the Type of a File of the glibc manual:

http://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html

Sign up to request clarification or add additional context in comments.

1 Comment

So, basically I will use st_mode and go through a series of if statements to determine what the file type is. Correct?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.