Basics of Sequential File Access in C Programming - dummies

Basics of Sequential File Access in C Programming

By Dan Gookin

The simplest way that C programming information is stored in a file is sequentially, one byte after the other. The file contains one long stream of data.

File access in C is simply another form of I/O. Rather than go to the display, the input or output goes into a file. A file is opened by using the fopen() function:

handle = fopen(filename,mode);

The fopen() function requires two arguments, both strings. The first is a filename; the second is a mode. The fopen() function returns a file handle, which is a pointer used to reference the file. That pointer is a FILE type of variable.

Mode File Open for Create File? Notes
“a” Appending Yes It adds to the end of an existing file; a file is created if it
doesn’t exist.
” a+” Appending and reading Yes Information is added to the end of the file.
“r” Reading No If the file doesn’t exist, fopen() returns an error.
“r+” Reading and writing No If the file doesn’t exist, an error is returned.
“w” Writing Yes The existing file is overwritten if the same name is used.
“w+” Writing and reading Yes The existing file is overwritten.

The mode is a string. Even when only one character is specified, it must be enclosed in double quotes.

After the file is open, you use the handle variable to reference the file as you read and write. The file I/O functions are similar to their standard I/O counterparts, but with an f prefix. To write to a file, you can use the fprintf(), fputs(), fputchar(), and similar functions. Reading from a file uses the fscanf(), fgets(), and similar functions.

You close the file by using the fclose() function with the file handle as its argument.

How to write text to a file

Write That File demonstrates the basic process of creating a new file, writing text to that file, and then closing file access.

WRITE THAT FILE

#include <stdio.h>
#include <stdlib.h>
int main()
{
 FILE *fh;
 fh=fopen("hello.txt","w");
 if(fh==NULL)
 {
 puts("Can't open that file!");
 exit(1);
 }
 fprintf(fh,"Look what I made!n");
 fclose(fh);
 return(0);
}

Line 6 creates the file handle, fh. It’s a pointer. The pointer stores the result of the fopen() function from Line 8. The file hello.txt is created using the “w” (write) mode. If the file exists, it’s overwritten.

The if statement checks to confirm that the file was properly opened. If it wasn’t, the value of fh is NULL, and appropriate action is taken.

The fprintf() function writes text to the file at Line 14. The format is the same as for printf(), although the file handle must be included as an argument.

Finally, Line 15 closes the file by using the fclose() function. This statement is a required step for any file access programming.

Exercise 1: Copy the source code from Write That File into your editor. Build and run the program.

The program’s output goes to a file, so you don’t see anything displayed when it’s run. Use your computer’s file browser to locate the file and open it. Or you can write a program that reads the text from that same file.

How to read text from a file

The standard C text-reading functions are used to read text from a file just as they read text from the keyboard. For reading text one character at a time, use the fgetc() function.

READ THAT FILE

#include <stdio.h>
#include <stdlib.h>
int main()
{
 FILE *fh;
 int ch;
 fh=fopen("hello.txt","r");
 if(fh==NULL)
 {
 puts("Can't open that file!");
 exit(1);
 }
 while((ch=fgetc(fh))!=EOF)
 putchar(ch);
 fclose(fh);
 return(0);
}

Line 9 in Read That File opens the file hello.txt for reading only. The file must exist or else an error occurs.

The while loop at Line 15 displays the file’s contents one character at a time. The fgetc() function reads one character from the file identified by handle fh. That character is stored in variable ch. The result is compared with the End of File constant. When there’s a match, the file has been completely read and the while loop stops. Otherwise, the character that’s read is displayed on Line 16.

Exercise 2: Create a new program by using the source code shown in Read That File. Build and run.

The program displays the contents of the file created by Exercise 1; otherwise, you see the error message.

Exercise 3: Modify your source code from Exercise 1 to write a second string to the file. Add the following statement after Line 14:

fputs("My C program wrote this file.n",fh);

Unlike using the puts() statement, you need to specify a newline character for fputs() output. Further, the file handle argument appears after the string, which is unusual for a C language file function.

The two file-writing functions fprintf() and fputs() write text to the file sequentially, one character after the other. The process works just like writing text to the screen, but instead those characters are saved in a file in permanent storage.

The fgets() function reads an entire string of text from a file. To make it work, you need an input buffer, the number of characters to read, and the file handle.

GULPING STRINGS OF TEXT

#include <stdio.h>
#include <stdlib.h>
int main()
{
 FILE *fh;
 char buffer[64];
 fh=fopen("hello.txt","r");
 if(fh==NULL)
 {
 puts("Can't open that file!");
 exit(1);
 }
 while(fgets(buffer,64,fh))
 printf("%s",buffer);
 fclose(fh);
 return(0);
}

The fgets() function appears at Line 15 as the while loop’s condition. That’s because fgets() returns a pointer to the string that’s read, and when no string is read, it returns a NULL. That value stops the loop. Otherwise, the printf() function at Line 16 displays the input.

The buffer size and the size of characters read in Gulping Strings of Text are identical. That’s because the at the end of the string is read from the file and isn’t interpreted as an end-of-file marker.

Exercise 4: Type the source code from Gulping Strings of Text into your editor. Build and run.