C – How to tell if a file is on a FAT system (see if it is really executable)

How to tell if a file is on a FAT system (see if it is really executable)… here is a solution to the problem.

How to tell if a file is on a FAT system (see if it is really executable)

I

work in an operating system-independent file manager, and I usually group files based on extensions. On Linux, I check if the file has executable permissions, and if so, I add it to the executable group.
This works well for Windows or Linux, but not so well if you combine them. For example, when using it on Linux and browsing the drive installed on Windows, all the files seem executable. I’m trying to find a way to ignore these files instead of adding them to the executable group.
My code (on Linux) uses stat:

#ifndef WINDOWS
stat(ep->d_name, &buf);
....
if(!files_list[i].is_dir && buf.st_mode & 0111)
files_list[i].is_exe=1;
#endif

Solution

The first part of the answer is to find out which file system the file is mounted on. To do this, you need to locate the file system using the st_dev field of the file’s stat information. (You can also do this by checking the file path, but you must check the symbolic link of each path element.)

You can then use getmntent_r() to cross-reference the mount table in the st_dev field and /proc/mounts. There is an example of that in a previous answer . The mnt_type field will give you text for the file system type, and you need to compare that string to the Windows file system list.

Once the file system is found, the only way to identify the executable is heuristic. As others have suggested, you can look at the file extension of the Windows executable and see the initial bytes of the file for the Linux executable. Don’t forget the executable script with the #! prefix, you may need to read into the jar file to find out if it contains an executable static main() method.

Related Problems and Solutions