FS utils treates directories as files?

Hendrik Hasenbein hhasenbe at techfak.uni-bielefeld.de
Tue Jun 9 10:48:54 UTC 2009


Thomas Backman wrote:
> 
> On Jun 9, 2009, at 11:03 AM, Ivan Voras wrote:
> 
>> Thomas Backman wrote:
>>> FreeBSD 8.0-CURRENT r193521 (Jun 5), bash:
>>> [root at chaos /usr/ports]# file /
>>> /: directory
>>> [root at chaos /usr/ports]# cat /
>>> �g��=[root at chaos /usr/ports]#
>>> [root at chaos /usr/ports]# cat /usr/ports/mail
>>>>>
>> This is the traditional behaviour because yes, directories are just
>> simply ordinary files with a special bit set to distinguish them. Other
>> systems might have modified "cat" to check if directories are files but
>> it's not standard.
>>
>> You can easily check this yourself. The following small program should
>> work on every unix-ish system:
>>
>> #include <stdio.h>
>> #include <stdlib.h>
>> #include <sys/fcntl.h>
>>
>> int main() {
>>     int fd, i;
>>     char buf[512];
>>     
>>     fd = open(".", O_RDONLY);
>>     read(fd, buf, 512);
>>     for (i = 0; i < 512; i++)
>>         printf("%4d ", buf[i]);
>> }
> 
> Yes, I realize that, and actually added a stat() call to cat to check
> for directories... before I realized it was true for other utils as well.
> I still think it's weird, though, and that the utils should check (as
> long as they return gibberish; less /etc on my GNU/Linux system actually
> shows a readable list of files - it seems as if less /etc == ls -al /etc
> | less). Is there *any* use for this behaviour, or is it simply there
> because nobody has added a check?

In rare cases you might want to look at the real content of the
directory file. Unix is all about having the choice. The linux variant
should give a hint of the form 'This file is a directory. Do you want to
'ls -la | less' instead? Like it does for 8bit content.

It isn't a GNU/linux feature. It depends on the distribution. Try a
slackware or a debian (debian does it sun style, but more /etc != less
/etc). They all handle it different. So you better don't use these
features if you want to retain portability.

(Example don't use #!/bin/sh and use bash features. It works on many
systems, but not all.)


Hendrik


More information about the freebsd-current mailing list