Zero byte files may be folders

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-04-15

I was working with an sftp server via an awful PHP library. A partner company was supposed to put their files in either the out or the in folder on their side of the server. They put, test - which I thought was a file - in the out folder. I tried reading it and it had 0 bytes inside, therefore causing the code problems.

Eventually, I noticed the PHP library assigned it a numerical type that was different to individual files. Therefore, between that and the 0 size, I ought to have thought to try cd-ing to it (and finding the files within)

In general, the stat function (in C, not the command line) has a st_mode piece of data. This is then used with a combination of bitwise macros and tests for quality of some constants to determine if something is a file/socket/directory etc.

In fact, the st_mode data contains info both about permissions and the file type (dir, socket, regular, etc?). To isolate to data about file type, we first bitwise AND with S_IFMT (0170000) and get some result in the format 0xx0000. Then the resulting 4 bits are compared with S_IFDIR and can determine file type:

BTW "By convention, the mode is a 16-bit value written out as a six-digit octal number WITH a leading zero"

directories: - S_IFDIR 0040000

files: (reg is for "regular file") - S_IFREG 0100000

Here's a macro in C:

#define S_ISREG( m ) (((m) & S_IFMT) == S_IFREG)

If it evaluates to non-zero, then the test is true. (0 and the test is false.) This makes sense because, e.g. bitwise AND-ing 0100 and 0100 will be 0100 which is none zero: i.e. this is not subtraction!

Resources