Text Files C

  • Opening and closing a file.
  • Character based I/O functions.
  • Using command line parameters.
  • String based I/O functions.
  • Formatted I/O functions.

Let us now study text files in detail, we will see how text files are opened and closed. We will see function for reading and writing characters and strings in a file. We will also see formatted I/O functions and learn the command line parameters.

Opening and closing a file

  • File is not opening.

Before opening a file we need to establish a file pointer.

FILE *fptr;

FILE is a structure defined in the header file “stdio.h”. This header files stores all the information regarding the file i.e. name of the file, in what mode it is opened, starting buffer address, a character pointer which points to the character being read. The above statement establishes a buffer area. Each file opened has its own file structure. Before processing any file, it must be opened.
On opening a file link is established between the program and operating system through the FILE structure, since operating system returns a pointer to the structure FILE. An opening a file associates the file name with buffer area. The file opening function is written as

fptr = fopen(file-name, file-type);

file-name = Name of data file to be opened.
File-type = Mode or manner in which data file will be used
(i.e. whether for reading, writing etc).

The following table gives the different modes in which a file can be opened.

different modes in which a file can be opened
When we have finished processing the file we need to close it explicitly. The syntax is fclose(fptr); If fclose is not present in the program, compiler automatically closes it at the end of the program execution.
The following program skeleton shows opening and closing file statements. The in between file processing statements are not included.

The header file “stdio.h”, must be included for it makes available the FILE structure. FILE * fptr defines fptr, as a pointer which points to structure of type FILE. The file opening statement searches for the file ‘sample.dat’ on disk. If it is present, it loads the file from the disk into memory in the read mode and returns a pointer to FILE and assigns it to fptr. It sets up a character pointer, which points to first character of the chunk of memory where the file has been loaded.

The last statement closes the data file. On closing a file the links between the file and the associated buffer are freed so that they can be used by other files.
It is seen that once the file is opened, all the file processing and file closing functions use the file pointer and not the name of the file.

File is not opening
There may be problem that file does not get opened. It can be for various reasons. If we need to open a file for reading, the file may not exist. If we want to open a file for writing, disk space may be insufficient.
In any case, if file opening function fails it returns a NULL which is defined in “stdio.h” as #define NULL 0
It is necessary to check whether file is successfully opened. It can be done as given below.

Character based I/O functions
Before using any file it is necessary to create the file. It can be created by

  • using any text editor directly
  • writing a program, to write into the file.

Program will consist of accepting character input from user and writing to the file using file processing function ‘fputc’. Any existing file or file created in the above manner can be read in any of the following way

  • Directly by using operating system command such as print or type
  • Using the text editor or word processor.
  • A program can be written to read the file.

In the program function fgetc reads characters from data file and putchar will display them on the screen. Individual data characters can also be processed as they are read. Thus fputc is a function used to write data character in a file.

int fputc(int ch, FILE *ptvar);

ch = Character to be written.
ptvar = File pointer.
fgetc is the counterpart of the function fputc and it is used to read a character from the file. It returns the character read to the calling program.

int fgetc(FILE * ptvar);

Let us write a program that copies the contents of one text file into another text file, character by character.

Let us study the program.
First line include the header file stdio.h in the program
Step 1 : defines two file pointers.
Step2 : opens the file pr1.c in the read mode and assigns the file pointer returned, to fs. Thus fs now points to the source file structure i.e. file which is to be read. The next if-block checks if fopen is successful, if not the program exist using the exit() statement.
Step 3 : opens the file pr2.c in the write mode and assigns the returned file pointer to ft. ft thus points to the target file. Next if-block checks if fopen is successful, if not the source file is closed (since it has been opened previously) and the program is terminated using exit() The main action is in the while loop. while(1) runs the while loop forever.
Step 4 : reads character from source file one by one and assigns to ch. If ch has a value of EOF, break causes control to be passed out of the while loop else fputc writes the character ch to the target file. At the end both files are closed with the function fclose.

What is ‘EOF’? When end of file is reached, fgetc() encounters a special character, which is returned as EOF. EOF is a macro defined in file stdio.h. EOF is given by a special character, whose ASCII value is 26. When file is created this character is inserted beyond the last character in the file. It can be retrieved from the keyboard by typing ctrl Z.

Using command line parameters
We have seen in the topic on function that main itself is a function. Till now we have always kept the
brackets after main as empty. Yes, argument can also be passed to main, as we pass argument to other
functions. The parenthesis of main may contain special arguments that allow parameters to be passed
to main from the operating system.
There are two arguments
argc = It is an integer which contains the count of, number of parameters passed to a program.
argv = It is an array of pointers to string, which contain all the parameters passed. The name of program occupies the place of argv[0] followed by the parameters.

Consider the previous program of copying one file to another. If the name of source code is filecopy.c then name of executable file is filecopy.exe. The source file and target files are either kept fixed within the program or they are accepted from the user while the program is running. But using command line parameters, we can pass the source file and the target file names as command line parameters. Since we pass the argument to main at the command prompt, they are called command line parameters.
Eg.
program can be run from the command prompt as
C:> FILECOPY pr1.c pr2.c
All the string at the command line are stored in memory and argv points to the first string which is name of the program.
argv[0] = filecopy
argv[1] = abc.c
argv[1] = abc.c
and argc is set to number of string. Here argc =3.
Using command line parameters the program can be written as

Since we require source file and target file names compulsorily, it is checked whether all arguments
are passed to the program. In (argc != 3) structure, if number of arguments are insufficient program is
exited. Rest of the program remains the same except the names of source file and target file are
replaced by argv[1] and argv[2].

If program name is followed by n parameters on the command line, argc will be set to (n + 1) and argv will have (n + 1) entries, index ranging from 0 to n. argc and argv are not assigned values explicitly as they are automatically initialized. If no parameter is passed to program, argc = 1 and argv[0] will contain name of program.(exe file). argv should have NULL as the ending element.

String based I/O
In some applications accessing files character by character is sufficient. Some files can be created and read more easily with programs that utilize string oriented library functions.
‘C’ provides two string functions for reading and writing to files.
fgets = It is used for reading a string from a file (including newline). Its general format is

char *fgets(char *line, int maxline, FILE *fp);

line = Address of array of characters where string is stored.
maxline = Maximum length of string. This argument prevent array from overflowing. At the most
(maxline – 1) characters will be read.
fp = It is the file pointer.
fgets return a line from the file on end of file or error it returns NULL.

fputs()
It is used for writing a string to a file. fputs does not automatically add a newline character to the end of the string. Its general format is

int fputs (char * line, FILE *fp);

line = It is the string which is to be written to the disk.
fp = It is the file pointer.
It returns EOF if error occurs otherwise last character is written.
fgets and fputs are analogous to gets and puts.

C File I/O and Binary File I/O
When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).
For example:

FILE *fp;

To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode);

In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as t. Using double backslashes escapes the key, so the string works as it is expected.
The modes are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer.
Here's a simple example of using fopen:

This code will open test.txt for reading in text mode. To open a file in a binary mode you must add a b to the end of the mode string; for example, "rb" (for the reading and writing modes, you can add the b either after the plus sign - "r+b" - or before - "rb+")
To close a function you can use the function

int fclose(FILE *a_file);

fclose returns zero if the file is closed successfully.
An example of fclose is

fclose(fp);

To work with text input and output, you use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument.
For example:

It is also possible to read (or write) a single character at a time--this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file:

int fgetc (FILE *fp);

Notice that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you're at the very end of the file, you can't get a character value--in this case, fgetc will return "EOF", which is a constant that indicates that you've reached the end of the file. To see a full example using fgetc in practice, take a look at the example here.
The fputc function allows you to write a character at a time--you might find this useful if you wanted to copy a file character by character. It looks like this:

int fputc( int c, FILE *fp );

Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics