08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6 ■ Characters

6.9 Read Characters from a File

In our examples so far, we have read characters typed at the keyboard. If we want to read

characters from a file (input.txt, say), we must declare a file pointer (in, say) and associate it

with the file using

FILE * in = fopen("input.txt", "r");

Once this is done, we could read the next character from the file into a char variable (ch, say) with

this statement:

fscanf(in, "%c", &ch);

However, C provides the more convenient function getc (get a character) for reading a character

from a file. It is used as follows:

ch = getc(in);

getc takes one argument, the file pointer (not the name of the file). It reads and returns the next

character in the file. If there are no more characters to read, getc returns EOF. Thus, getc works

exactly like getchar except that getchar reads from the keyboard while getc reads from

a file.

To illustrate, let us write a program that reads one line of data from a file, input.txt, and

prints it on the screen. This is shown as Program P6.9.

Program P6.9

#include <stdio.h>

int main() {

char ch;

FILE *in = fopen("input.txt", "r");

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

putchar(ch);

putchar('\n');

fclose(in);

}

This program uses the standard function putchar to write a single character to the standard

output. (Like getchar, putchar is a macro but the distinction is not important for our purposes.)

It takes a character value as its only argument and writes the character in the next position in

the output. However, if the character is a control character, the effect of the character is produced.

For example,

putchar('\n');

will end the current output line – the same effect as if “Enter” or “Return” is pressed.

156

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!