08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6 ■ Characters

The program reads one character at a time from the file and prints it on the screen using

putchar. It does this until \n is read, indicating that the entire line has been read. On exit from the

while loop, it uses putchar('\n') to terminate the line on the screen.

Be careful, though. This program assumes that the line of data is terminated by an end-of-line

character, \n (generated when you press “Enter” or “Return”). However, if the line is not terminated

by \n, the program will ‘hang’—it will be caught in a loop from which it cannot get out (we say it will

be caught in an infinite loop). Why?

Because the while condition ((ch = getc(in)) != '\n') will never become false (this

happens when ch is '\n') since there is no \n to be read. But, as discussed before, when we reach

the end-of-file, the value returned by getchar, and now also by getc, is the symbolic constant EOF

defined in stdio.h. Knowing this, we could easily fix our problem by testing for \n and EOF in the

while condition, thus:

while ((ch = getc(in)) != '\n' && ch != EOF)

Even if \n is not present, getc(in) will return EOF when the end of the file is reached, and the

condition ch != EOF would be false, causing an exit from the loop.

6.10 Write Characters to a File

Suppose we want to write characters to a file (output.txt, say). As always, we must declare a file

pointer (out, say) and associate it with the file using

FILE * out = fopen("output.txt", "w");

If ch is a char variable, we can write the value of ch to the file with

fprintf(out, "%c", ch);

C also provides the function putc (put a character) to do the same job. To write the value of ch to

the file associated with out, we must write:

putc(ch, out);

Note that the file pointer is the second argument to putc.

6.10.1 Echo Input, Number Lines

Let us expand the example on the previous page to read data from a file and write back the same

data (echo the data) to the screen with the lines numbered starting from 1.

The program would read the data from the file and write it to the screen, thus:

1. First line of data

2. Second line of data

etc.

157

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!