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.
Consider the program
#include < stdio.h > main() { char i[40]; int stopsignal; do { stopsignal = scanf("%s", i); printf("%s\n",i); } while (stopsignal != EOF); }
C lets you do whatever you like, no matter how harmful.