This tutorial shows you how to read and display the contents of a sequential file onscreen using the C++ programming language.
The following code reads data from a sequential file and displays it onscreen. This example demonstrates how to read a simple data structure from a sequential file, such as a text file containing lines of comma-separated values.
This simple program reads the words contained in a sequential file, puts them into a string, and then displays them onscreen.
#define BUFFSIZE 255
void main (int argc, char* argv[])
{
FILE *fp;
char buffer[BUFFSIZE];
fp = fopen (argv [1],"r");
if (fp == NULL) {
printf("%s file does not exist\n", argv[1]);
exit(1);
}
while (!feof(fp))
{
fgets(buffer, BUFFSIZE, fp);
puts(buffer);
}
fclose(fp);
}
We will define a file pointer as a named string of length 255. It’s called a file pointer because it points to a specific part of a file.
We will open the sequential file, whose name is provided as a command-line argument, in read-only mode and set the fp file pointer to point at it.
If the file cannot be opened in read-only mode because it doesn’t exist or because the user does not have enough permissions, an error message will be displayed and the program will terminate.
This script opens the file in read-only mode and waits until the end of the file is reached. If the file doesn’t open successfully, the script prints an error message to the standard output and ends.
First you need to get each line of input into a buffer string. To do this you use the fgets function to read one line at a time. The line read from the file is then assigned to the buffer string.
The content in the buffer string must be displayed onscreen, then the user types in a new line to create another buffer string.
When a program ends, the file it has been working on is closed and then the resources used by the file are released back to the operating system.