http://qs321.pair.com?node_id=770191

Selvakumar has asked for the wisdom of the Perl Monks concerning the following question:

Is there any possibilities to find the file type without looking the extension. For example i have a PDF file without ".pdf" extension. How can i find what kind of file is this?

Replies are listed 'Best First'.
Re: understanding file type
by tomfahle (Priest) on Jun 10, 2009 at 05:57 UTC

    Also have a look at File::LibMagic

    #!/usr/bin/perl use warnings; use strict; use File::LibMagic ':easy'; my @files = qw( /bin/ls /etc/localtime /etc/timezone /etc/motd ); foreach my $file ( @files ) { print "$file:\n\t", MagicFile( $file ), "\n"; }

    which yields

    /bin/ls: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for +GNU/Linux 2.6.8, dynamically linked (uses shared libs), stripped /etc/localtime: timezone data /etc/timezone: ASCII text /etc/motd: symbolic link to `/var/run/motd'

    on my Linux Box.

Re: understanding file type
by ikegami (Patriarch) on Jun 10, 2009 at 05:13 UTC
Re: understanding file type
by Bloodnok (Vicar) on Jun 10, 2009 at 09:09 UTC
    You don't say on which platform you're running, but if it's *NIX, then file(1) (which uses /etc/magic) is your friend - see man file.

    A user level that continues to overstate my experience :-))
Re: understanding file type
by nikosv (Deacon) on Jun 10, 2009 at 08:01 UTC
    binary files have a unique identifier embedded into the header of the file.eg a PDF file starts with '%PDF-1.3' use a Hex editor and look at the header of the file, or programmatically read the first few bytes from the header and identify the file format.basically look at the documentation of the format