Redirection and Files

I l @ ve RuBoard

Redirection and Files

Input and output involve functions, data, and devices. Consider, for instance, the echo_eof.c program. It uses the input function getchar () . The input device (we have assumed) is a keyboard, and the input data stream consists of individual characters . Suppose you want to keep the same input function and the same kind of data, but want to change where the program looks for data. A good question to ask (and to answer) is "How does a program know where to look for its input?"

By default, a C program using the standard I/O package looks to the standard input as its source for input. This is the stream identified earlier as stdin . It is whatever has been set up as the usual way for reading data into the computer. It could be magnetic tape, punched cards, a teletype, or (as we will continue to assume) your keyboard. A modern computer is a suggestible tool, however, and you can influence it to look elsewhere for input. In particular, you can tell a program to seek its input from a file instead of from a keyboard. There are two ways to get a program to work with files. One way is to explicitly use special functions that open files, close files, read files, write in files, and so forth. That method we'll save for Chapter 12. The second way is to use a program designed to work with keyboard and screen, but to redirect input and output along different channels, to and from files, for example. In other words, you reassign the stdin stream to file. The getchar() program continues to get its data from the stream, not really caring from where the stream gets its data. This approach is more limited in some respects than the first, but it is much simpler to use. It is the one you will use now.

One major problem with redirection is that it is associated with the operating system, not C. However, the most popular C environments (UNIX and DOS 2.0 and later) feature redirection, and some C implementations simulate it on systems lacking the feature. We'll look at the UNIX and DOS versions.

UNIX and DOS Redirection

UNIX and current DOS versions enable you to redirect both input and output. Redirecting input enables your program to use a file instead of the keyboard for input, and redirecting output enables it to use a file instead of the screen for output.

Redirecting Input

Suppose you have compiled the echo_eof.c program and placed the executable version in a file called echo_eof (or echo_eof.exe on DOS systems). To run the program, type the executable file's name :

 echo_eof 

The program runs as described earlier, taking its input from the keyboard. Now suppose you want to use the program on a text file called words . A text file is one containing text, that is, data stored as human-readable characters. It could be an essay or a program in C, for example. A file containing machine language instructions, such as the file holding the executable version of a program, is not a text file. Because the program works with characters, it should be used with text files. All you need do is enter this command instead of the previous one:

 echo_eof < words 

The < symbol is a UNIX (and DOS) redirection operator. It causes the words file to be associated with the stdin stream, channeling the file contents into the echo_eof program. The echo_eof program itself doesn't know (or care) that the input is coming from a file instead of the keyboard. All it knows is that a stream of characters is being fed to it, so it reads them and prints them one character at a time until the end of file shows up. Because C puts files and I/O devices on the same footing, the file is now the I/O device . Try it!

Redirection Sidelights

With UNIX and DOS, the spaces on either side of the < are optional. Some systems, such as AmigaDOS, support redirection but don't allow a space between the redirection symbol and the filename.

Here is a sample run for one particular words file; the $ is one of the two standard UNIX prompts. On a DOS system, you would see the DOS prompt, perhaps an A> or C> .

 $ echo_eof < words The world is too much with us: late and soon, Getting and spending, we lay waste our powers: Little we see in Nature that is ours; We have given our hearts away, a sordid boon! $ 

Well, that time we got our words' worth.

Redirecting Output

Now suppose you want to have echo_eof send your keyboard input to a file called mywords . Then you can enter the following and begin typing:

 echo_eof > mywords 

The > is a second redirection operator. It causes a new file called mywords to be created for your use, and then it redirects the output of echo_eof (that is, a copy of the characters you type) to that file. The redirection reassigns stdout from the display device (your screen) to the mywords file instead. If you already have a file with the name mywords , normally it would be erased and then replaced by the new one. (Some UNIX systems, however, give you the option of protecting existing files.) All that appears on your screen are the letters as you type them, and the copies go to the file instead. To end the program, type Ctrl+D (UNIX) or Ctrl+Z (DOS) at the beginning of a line. Try it. If you can't think of anything to type, just imitate the next example. In it, we use the $ UNIX prompt. Remember to end each line by pressing Enter to send the buffer contents to the program.

 $ echo_eof > mywords You should have no problem recalling which redirection operator does what. Just remember that each operator points in the direction the information flows. Think of it as a funnel. [Ctrl+D] $ 

After the Ctrl+D or Ctrl+Z is processed , the program terminates and your system prompt returns. Did the program work? The UNIX ls command or DOS dir command, which lists filenames, should show you that the file mywords now exists. You can use the UNIX cat or DOS type command to check the contents, or you can use echo_eof again, this time redirecting the file to the program:

 $  echo_eof < mywords  You should have no problem recalling which redirection operator does what. Just remember that each operator points in the direction the information flows. Think of it as a funnel. $ 
Combined Redirection

Now suppose you want to make a copy of the file mywords and call it savewords . Just issue this next command,

 echo_eof <mywords> savewords 

and the deed is done. The following command would have served as well because the order of redirection operations doesn't matter:

 echo_eof > savewords < mywords 

Beware. Don't use the same file for both input and output to the same command.

 echo_eof < mywords > mywords....<--WRONG 

The reason is that > mywords causes the original mywords to be truncated to zero length before it is ever used as input.

In brief, here are the rules governing the use of the two redirection operators < and > with UNIX or DOS:

  • A redirection operator connects an executable program (including standard UNIX commands) with a data file. It cannot be used to connect one data file to another, nor can it be used to connect one program to another program.

  • Input cannot be taken from more than one file, nor can output be directed to more than one file by using these operators.

  • Normally, spaces between the names and operators are optional, except occasionally when some characters with special meaning to the UNIX shell or DOS are used. We could, for example, have used echo_eof<words .

You have already seen several proper examples. Here are some wrong examples, with addup and count as executable programs and fish and beets as text files:

fish > beets <-- violates the first rule
addup < count <--violates the first rule
addup < fish < beets <--violates the second rule
count > beets fish <--violates the second rule

UNIX and DOS also feature the >> operator, which enables you to add data to the end of an existing file, and the pipe operator ( ), which enables you to connect the output of one program to the input of a second program. See a UNIX book, such as UNIX Primer Plus, Second Edition (Waite, Prata, and Martin; Indianapolis: Sams Publishing), for more information on all these operators.

Comment

Redirection enables you to use keyboard-input programs with files. For this to work, the program has to test for the end of file. For example, Chapter 7 presents a word-counting program that counts words up to the first character. Change ch from type char to type int , and replace '' with EOF in the loop test, and you can use the program to count words in text files.

Redirection is a command-line concept because you indicate it by typing special symbols on the command line. If you are not using a command-line environment, you might still be able to try the technique. First, some integrated environments have menu options that let you indicate redirection. Second, the Metrowerks CodeWarrior and the Symantec C/C++ compilers have a mechanism for simulating command-line arguments (see Chapter 11, "Character Strings and String Functions" ) that also supports redirection. Listing 8.3 shows a Mac-oriented version of Listing 8.2 that enables redirection.

Listing 8.3 The mac_eof.c program.
 /* mac_eof.c -- enables redirection on the Mac */ #include <stdio.> #include <console.h>  /* declares ccommand() */ int main(int argc, char *argv[])    {   int ch;   argc = ccommand(&argv);   while ((ch = getchar()) != EOF)        putchar(ch);   return 0;    } 

Chapter 11 discusses the altered function heading. The main point is that when the program executes the ccommand() function, it displays a dialog box that allows you to specify files be used for input and output.

Summary: How to Redirect Input and Output

With most C systems, you can use redirection, either for all programs through the operating system or else just for C programs, courtesy of the C compiler. In the following, let prog be the name of the executable program and let file1 and file2 be names of files.

Redirecting Output to a File:

 prog >file1 

Redirecting Input from a File: <

 prog <file2 

Combined Redirection:

 prog <file2 >file1 prog >file1 <file2 

Both forms use file2 for input and file1 for output.

Spacing:

Some systems require a space to the left of the redirection operator and no space to the right. Other systems (UNIX, for example) accept either spaces or no spaces on either side.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net