You are not logged in.
I am working on a c program which displays all the directories and files under each directory.
I want to know what kind of file each is. Like, is the file an ascii text file or english text or a c file.
if it is an executable, is it an binary file or a shell script.
I was told to look inside the file to achieve this.
How can I do this?
the man pages are quite confusing and difficult to understand.Can anyone suggest something on this.
Thanks in advance
There are different kinds of file type:
- The one you get from stat()/fstat(), e.g. regular file, directory, fifo, device file, link, etc. and the file permissions and ownership information.
- The type of file in the usage sense. Most often you can find this one by looking at the file extension (the last part after the '.'). So foo.png is a PNG image file, and you know it because it ends in .png.
- You can look at the beginning of the file and try to guess what it is. In the case of a PNG file you'd look for the PNG header which all PNG files have. This is what the command "file" does. So to find out how to do it you can look at its source code (it uses a database with known file types it checks against). You can also run the file command and use its output instead of doing it yourself.
Read the manpage of stat()/fstat() for stat information.
E.g. to check if it's a regular file you can use the S_ISREG() macro.
As for figuring out what kind of file it is from the first few bytes, that's much more complicated. Go read the file source code to know how you can do that. But perhaps it's better to call the program "file" from your program with the -m option, or whatever suits your need.