2

I am working on displaying output like ls command (just ls, no options). And I have a working program using the system calls. But I experienced a strange behavior while testing as shown below.

$ ls 
a b c
$ ls > somefile
$ cat somefile
a
b
c

so, as you see the output is written one file per file, NO ADDITIONAL SWITCHES WERE GIVEN TO LS. You can test it out. So from above I infer, ls command has some built-in logic to display it one per line if written to a file via redirection.

To add to the puzzle, I believe it's the shell that interprets the redirection.

So I am confused I would like to kown what exactly is making the output one per line if redirected to a file? Any hint?

mtk
  • 27,530
  • 35
  • 94
  • 130
  • 1
    see http://unix.stackexchange.com/questions/157285/why-does-ls-wc-l-show-the-correct-number-of-files-in-current-directory – jimmij Sep 02 '15 at 15:54
  • In both ls invocations, the output is redirected to a file. In the first case, a device file, in the second case, presumably a regular file, in anycase not a terminal device file, as otherwise you'd see a b c as well. – Stéphane Chazelas Sep 02 '15 at 16:02

1 Answers1

3

Usually by testing if a relevant filehandle is attached to a tty:

% perl -le 'print -t STDOUT ? "yes" : "no"'
yes
% perl -le 'print -t STDOUT ? "yes" : "no"' > out
% < out
no
% 

Or via C, something like:

#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

...

int foo;
if (ioctl(STDIN_FILENO, FIONREAD, &foo) == -1) {
    printf("yes\n");
} else {
    printf("no\n");
}
thrig
  • 34,938