Redirection

Chapter: Files
...Section: Redirection

The programs above took input from the keyboard and sent output to your screen. If you want the same programs to read input from a file, you can use input redirection. If the executable prog expects keyboard input, then by typing prog < myfile.txt the same program will run but take its input from the file myfile.txt. In preparation for the next exercise, create a file nums.txt containing

1 2 3
4 5 6

Take the program from the last section and put it in a loop. For now, we'll use a do while (true) infinite loop.

#include < stdio.h >
main() {
  int i;
  int status;
  do {
    status = scanf("%d", &i);
    printf("I just read %d and had a status of %d\n", i, status);
  } while (1);
}

Before you run this program, you need to know how to kill runaway infinite looping programs. In a regular shell, issue a single CTRL-c. In some emacs shells you'll need to issue a double CTRL-c CTRL-c.


Exercise 3

  1. What happens when you compile this program and run it with good data?
  2. What happens when you run it with bad data?
  3. What happens when you run it with input redirected from nums.txt?
  4. What happens when you give this program good data from the keyboard followed by CTRL-d? (To issue a CTRL-d in some Emacs shells, you need to type CTRL-c followed by CTRL-d.)
  5. Why do you think I used the name status for that int?
  6. Rewrite the while condition so that the program will terminate when you give it a CTRL-d.


Consider the program

#include < stdio.h >
main() {
  char i[40];
  int stopsignal;
  do {
    stopsignal = scanf("%s", i);
    printf("%s\n",i);
  } while (stopsignal != EOF);
}

Exercise 4

  1. What does it do?
  2. What if you redirect so input comes from its own source file?
  3. What if you redirect so output goes to its own source file?
  4. What if you redirect so output goes to its own executable?


C lets you do whatever you like, no matter how harmful.


rhyspj@gwu.edu