UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2006-11-14 11:20 PM

vijraj
Member
Registered: 2006-10-23
Posts: 23

Re: filetypes

Hi Everyone!

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

Offline

#2 2006-11-14 11:42 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,230

Re: filetypes

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.

Offline

#3 2006-11-15 02:12 AM

vijraj
Member
Registered: 2006-10-23
Posts: 23

Re: filetypes

Thankyou!,i3839.
Actually I think I have to do it myself.Let me try it.
Thanks.

Offline

#4 2006-11-15 03:05 AM

vijraj
Member
Registered: 2006-10-23
Posts: 23

Re: filetypes

Hi i3839!
Can u give me an example of how to read a file for bytes and then decide what it is.I am all confused.
Like, stat returned and it says, it is a regular file.
So from now what should I do?
Thanks for ur help.

Offline

#5 2006-11-15 02:38 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,230

Re: filetypes

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.

Offline

Board footer

Powered by FluxBB