The C Column

See all articles from CATS v8 n2
Author(s): Tim Swenson
Publication: CATS Newsletter
Pub Details: CATS v8 n2 (Volume 8, Issue 2)
Date: July 1990
Pages: 4-5

As promised last month, I’ll talk about how C accesses files.

The simplest way to discuss how C handles files is to take a look at a C program that uses it. Look at program number 5. This program asks the user for a file name. It then opens the file, reads in a character and prints it out the screen. This goes on for the entire file.

The program declares a character array of size 20 to be hold the file name. It then declares the integer fd to hold the file ID. When a file is opened, C assigns a number to it. This number is returned from the fopen command to the variable fd.

Note the syntax of the fopen command. The file name is sent into the function along with a string that specifies if the file is for reading or writing. If we wanted to open a file to write to, we would have used “w” instead of “r”.

The next couple of lines checks to see if the file was opened sucessfully. If the file was not opened (there was some error like a bad file name) fd will be returned as NULL (a predefined constant).

Instead of using getch the function getc is used. Where getch defaults to the keyboard, getc needs a file ID to know where to get it’s input. In our case we use fd.

We exit the while loop when the program reaches the end of the file (EOF). After the program exits the while loop, we use the fclose function to close the file. We must tell fclose which file to close. If we do not close the file, we may loose the file.

/* prog 5 */
#include <stdio_h>

main() {
char file[20];
int c, fd;

printf("Enter file: ");
gets(file);

fd=fopen(file,"r");
if (fd == NULL) {
printf("File open Error");
abort(1);
}
while ((c=getc(fd))!=EOF) {
putchar(c);
}
fclose(fd);
}

Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.