0% found this document useful (0 votes)
16 views

BIT104 SLM Library - SLM - Unit 14

Uploaded by

pavanmay227597
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

BIT104 SLM Library - SLM - Unit 14

Uploaded by

pavanmay227597
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Principles of C Programming Unit 14

Unit 14 File Management

Structure:
14.1 Introduction
Objectives
14.2 Defining and Opening a File
14.3 Closing Files
14.4 Input/output Operations on Files
Read or Write One Character at a Time
Read or Write One Line of Text at a Time
Formatted I/O
Predefined Streams
14.5 Error Handling during I/O Operations
14.6 Random Access to Files
14.7 Command Line Arguments
14.8 Summary
14.9 Terminal Questions
14.10 Answers
14.11 Exercises

14.1 Introduction
In the previous unit, we discussed the dynamic memory allocation in C.
Dynamic memory allocation is the process of allocating memory at run time.
We learned four memory management functions that can be used for
allocating and freeing memory during program execution. We also
discussed important data structure called linked list. A linked list is a chain
of nodes. Each node consists of data items and a pointer that points to the
next node in the list. The last item has a null pointer to signify the end of the
list.
In C, a file refers to a disk file, a terminal, a printer, or a tape drive. In other
words, a file represents a concrete device with which we want to exchange
information. Before we perform any communication to a file, we have to
open the file. We also need to close the opened file after we finish
exchanging information with it.

Sikkim Manipal University B2074 Page No.: 298


Principles of C Programming Unit 14

A stream is a series of bytes through which we read or write data to a file.


Unlike a file, which targets a specific I/O (Input /Output) device, a stream is
device independent. All streams have the same behavior regardless of
whatever device they are associated with. To perform I/O operations, we
can read from or write to any type of file by simply associating a stream to
the file.
There are two formats of streams. The first one is called the text stream,
which consists of a sequence of characters (that is, text data). Depending
on the system, each line of characters in a text stream may be terminated
by a newline character (‘\n’). Text streams are used for textual data, which
has a consistent appearance from one environment to another or from one
machine to another.
The second format of streams is called the binary stream, which is a series
of bytes, for example, the content of an executable program file. Binary
streams are primarily used for non-textual data, where the exact contents of
the data are maintained without regard to appearance.
In C, a memory area that is temporarily used to store data before it is sent to
its destination is called a buffer. With the help of buffers, the operating
system can improve efficiency by reducing the number of accesses to I/O
devices (that is, files).
Access to a disk or other I/O device is generally much slower than direct
access to memory. Several I/O operations can be performed on a buffer that
represents the I/O file, instead of the file itself. For example, if several write
operations are sent to a buffer, they are kept in memory until it is time to
save, or commit, the new data to the actual device. This process is known
as flushing the buffer. So instead of several write operations in a row, each
going to the slow disk device, they all take place in the memory buffer and
the disk device will only be accessed once, when the buffer is flushed. By
default, all I/O streams are buffered. Buffered I/O is also called high-level
I/O, whereas unbuffered I/O (directly to the device) is called low-level I/O.
In this unit, we will discuss how to take control of input and output by
opening our own streams, perhaps connected to data files, which we can
read from and write to.

Sikkim Manipal University B2074 Page No.: 299


Principles of C Programming Unit 14

Objectives:
After studying this unit, you should be able to:
 open file and control input and output
 connect to file and able to read from the file and write to the file using file
pointers.
 check for error during I/O operations on files.
 implement the Random Access functions to allow control over the
implied read/write position in the file.
 supply a parameter to a program when the program is invoked using a
command line arguments.

14.2 Defining and Opening a File


Let us focus on how to open and close a disk data file and how to interpret
error messages returned by I/O functions.
Pointers of FILE: The FILE structure is the file control structure defined in
the header file stdio.h. It is a data structure which holds the information the
standard I/O library needs to keep track of the file. A pointer of type FILE is
called a file pointer, which references a disk file. A file pointer is used by a
stream to conduct the operation of the I/O functions. For instance, the
following defines a file pointer called fptr:
FILE *fptr;
In the FILE structure there is a member, called the file position indicator,
which points to the position in a file where data will next be read from or
written to.
If we were reading from two files at once we would probably use two file
pointers:
FILE *fptr1, *fptr2;
If we were reading from one file and writing to another, we might declare an
input file pointer and an output file pointer:
FILE *ifptr, *ofptr;
Like any pointer variable, a file pointer is not good until it is initialized to
point to something. In fact, no variable of any type is much good until it has
been initialized.

Sikkim Manipal University B2074 Page No.: 300


Principles of C Programming Unit 14

Opening a File: The C I/O function fopen() opens a file and associates a
stream with the opened file. We need to specify the method of opening the
file and the filename as arguments to the fopen() function. The syntax for
the fopen() function is
#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);
Here filename is a char pointer that references a string containing a
filename. The filename is given to the file that is about to be opened by the
fopen() function. On the other hand, mode points to another string that
specifies the manner in which to open the file. The fopen() function returns a
pointer of type FILE. If an error occurs during the procedure of opening a file,
the fopen() function returns a null pointer.
The mode parameter is made by a combination of the characters r (read), w
(write), b(binary), a (append), and + (update). When we use append mode,
and the file already exists, the contents of the file will be preserved and new
data that we write will be added to the end. If the file does not already exist,
it will be created. This is in contrast to w, which always attempts to create a
new file, and will discard whatever data may already be in the file. Using the
+ character sets the mode to both reading and writing. When we use r, the
file must already exist; if it does not, the call will fail.
The following list shows the possible ways to open a file by various strings
of modes:
• “r” opens an existing text file for reading.
• “w” creates a text file for writing.
• “a” opens an existing text file for appending.
• “r+” opens an existing text file for reading or writing.
• “w+” creates a text file for reading or writing.
• “a+” opens or create a text file for appending.
• “rb” opens an existing binary file for reading.
• “wb” creates a binary file for writing.
• “ab” opens an existing binary file for appending.
• “r+b” opens an existing binary file for reading or writing.
• “w+b” creates a binary file for reading or writing.
• “a+b” opens or creates a binary file for appending.

Sikkim Manipal University B2074 Page No.: 301


Principles of C Programming Unit 14

Note that we might see code where the mode is given as “rb+” instead of
“r+b”. These two strings are equivalent. Similarly, “wb+” is the same as
“w+b”; “ab+” is equivalent to “a+b”.
The following statements try to open a file called test.txt:
FILE *fptr;
if ((fptr = fopen(“test.txt”, “r”)) == NULL){
printf(“Cannot open test.txt file.\n”);
exit(1);
}
Here “r” is used to indicate that a text file is about to be opened for reading
only. If an error occurs when the fopen() function tries to open the file, the
function returns a null pointer. However this happens if test.txt does not
already exist. Then an error message is printed out by the printf() function
and the program is aborted by calling the exit() function with a nonzero
value.
To open the file output.dat for writing we might call fopen() using mode "w"
which indicates writing:
ofptr = fopen("output.dat", "w");
It is common to collapse the call to fopen and the assignment in with the
test:

if((ifp = fopen("input.dat", "r")) == NULL)


{
printf("can't open file\n");
exit or return
}

We do not have to write these “collapsed'' tests if we are not comfortable


with them, but since these are commonly used by coders, it is essential that
we should be able to read them.
Self Assessment Questions
1. The type FILE is predefined in the header file ___________.
2. The fopen function tries to open the file and If an error occurs it returns
___________. (True/False)
Sikkim Manipal University B2074 Page No.: 302
Principles of C Programming Unit 14

14.3 Closing Files


After a disk file is read, written, or appended with new data, we have to
disassociate the file from a specified stream by calling the fclose() function.
The syntax for the fclose() function is:
#include <stdio.h>
int fclose(FILE *stream);
Here stream is a file pointer that is associated with a stream to the opened
file. If fclose() closes a file successfully, it returns 0. Otherwise, the function
returns EOF.
Normally, the fclose() function fails only when the disk is removed before the
function is called or there is no more space left on the disk.
Because all high-level I/O operations are buffered, the fclose() function
flushes data left in the buffer to ensure that no data will be lost before it
disassociates a specified stream with the opened file.
Note that a file that is opened and associated with a stream has to be
closed after the I/O operation. Otherwise, the data saved in the file may be
lost and some unpredictable errors might occur during the execution of
program. In addition, failing to close a file when we are done with it may
prevent other programs (or users of program) from accessing the file later. If
we forget to close a file, it will be closed automatically when the program
exits.
Self Assessment Questions
3. Closing a file simply involves calling fclose with the ___________ as its
argument.
4. If we forget to close a file, it will be closed automatically when the
program exits. (True/False)

14.4 Input/output Operations on Files


In this section, we will discuss following I/O operations on files:
• Read or write one character at a time.
• Read or write one line of text at a time.
• Formatted I/O

Sikkim Manipal University B2074 Page No.: 303


Principles of C Programming Unit 14

14.4.1 Read or Write One Character at a Time:


Among the C I/O functions, there is a pair of functions, fgetc() and fputc(),
that can be used to read from or write to a disk file one character at a time.
The C library function fgetc() gets the next character (an unsigned char)
from the specified stream and advances the position indicator for the stream.
The syntax for the fgetc() function is
#include <stdio.h>
int fgetc(FILE *fptr);
Here fptr is the file pointer that is associated with a stream on which the
operation is to be performed. The function then returns the value of an int
that is converted from the character. EOF is returned if fgetc() encounters
the end of the file, or if there is an error.
The syntax for the fputc() function is
#include <stdio.h>
int fputc(int c , FILE *fptr);
Here c is an int value that represents a character. In fact, the int value is
converted to an unsigned char before being outputted. fptr is the file pointer
that is associated with a stream. The fputc() function returns the character
written if the function is successful; otherwise, it returns EOF. After a
character is written, the fputc() function advances the associated file pointer.
Example 14.1: Our own fgetline function which reads from an arbitrary file
pointer:
#include <stdio.h>

/* Read one line from fp, */


/* copying it to line array (but no more than max chars). */
/* Does not place terminating \n in line array. */
/* Returns line length, or 0 for empty line, or EOF for end-of-file. */

int fgetline(FILE *fp, char line[], int max)


{
int nch = 0;
int c;

Sikkim Manipal University B2074 Page No.: 304


Principles of C Programming Unit 14

max = max - 1; /* leave room for '\0' */

while((c = fgetc(fp)) != EOF)


{
if(c == '\n')
break;

if(nch < max)


{
line[nch] = c;
nch = nch + 1;
}
}

if(c == EOF && nch == 0)


return EOF;

line[nch] = '\0';
return nch;
}
Now we could read one line from ifp by calling
char line[MAXLINE];
...
fgetline(ifp, line, MAXLINE);

Program 14.1: The program to display content of file on screen.

#include <stdio.h>
main(void)
{
FILE *fp;
char filename[]= “Test.txt”;
if ((fp = fopen(filename, “r”)) == NULL){
printf(“Cannot open %s.\n”, filename);
exit(1);
}
else

Sikkim Manipal University B2074 Page No.: 305


Principles of C Programming Unit 14

{
while (1)
{
ch = fgetc (fp) ;
if ( ch == EOF )
break ;
printf ( "%c", ch ) ;
}
fclose(fp);
}
return 0;
}

If an error occurs when we try to open the text file, the fopen() function
returns a null pointer, and prints a warning message, and exit the program.
Otherwise, reads the content of file one character at time and display it on
screen.

14.4.2 Read or Write One Line of Text at a Time:


Besides reading or writing one character at a time, we can also read or write
one character line at time. There is a pair of C I/O functions, fgets() and
fputs(), that allows us to do so. The syntax for the fgets() function is
#include <stdio.h>
char *fgets(char *s, int n, FILE *stream);
Here argument s references a character array that is used to store
characters read from the opened file pointed to by the file pointer stream. n
specifies the maximum number of array elements. If it is successful, the
fgets() function returns the char pointer s. If EOF is encountered, the fgets()
function returns a null pointer and leaves the array untouched. If an error
occurs, the function returns a null pointer, and the contents of the array are
unknown.
The fgets() function can read up to n-1 characters, and can append a null
character after the last character fetched, until a newline or an EOF is
encountered. Note that if a newline is encountered during the read operation,
the fgets() function includes the newline in the array. This is different from

Sikkim Manipal University B2074 Page No.: 306


Principles of C Programming Unit 14

what the gets() function does. The gets() function just replaces the newline
character with a null character.
The syntax for the fputs() function is
#include <stdio.h>
int fputs(const char *s, FILE *stream);
Here argument s points to the array that contains the characters to be
written to a file associated with the file pointer stream. The const modifier
indicates that the content of the array pointed to by s cannot be changed by
the fputs() function. If it fails, the fputs() function returns a nonzero value;
otherwise, it returns zero. Note that the character array must include a null
character at the end of the string as the terminator to the fputs() function.
Also, unlike the puts() function, the fputs() function does not insert a newline
character to the string written to the file.
14.4.3 Formatted I/O
We have dealt with reading and writing only characters and strings. What if
we want to read or write numbers from/to file? Further the question that
arises is what if we desire to read/write a combination of characters, strings
and numbers? As we have discussed, the two C library functions scanf()
and printf() can be used to read or write formatted data through the
standard I/O (that is, stdin and stdout). Among the C disk file I/O functions,
there are two equivalent functions, fscanf() and fprintf(), that can do the
same jobs as the scanf() and printf() functions. In addition, the fscanf() and
fprintf() functions allow the programmer to specify I/O streams other than
stdin and stdout.
The syntax for the fscanf() function is
#include <stdio.h>
int fscanf(FILE *stream, const char *format, …);
Here stream is the file pointer associated with an opened file. Here
argument format (whose usage is the same as in the scanf() function) is a
char pointer pointing to a string that contains the format specifiers. If
successful, the fscanf() function returns the number of data items read.
Otherwise, the function returns EOF.
The syntax for the fprintf() function is
#include <stdio.h>
int fprintf(FILE *stream, const char *format, ...);
Sikkim Manipal University B2074 Page No.: 307
Principles of C Programming Unit 14

Here stream is the file pointer associated with an opened file format, whose
usage is the same as in the printf() .function, is a char pointer pointing to a
string that contains the format specifiers. If successful, the fprintf() function
returns the number of formatted expressions. Otherwise, the function
returns a negative value.
Program 14.2: Writing a data to the file using fprintf() function.

#include <stdio.h>
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}
14.4.4 Predefined Streams
Besides the file pointers which we explicitly open by calling fopen, there are
also three predefined streams. In nearly all the previous units, we have
been calling printf to print formatted output to the “standard output''. We
have also been calling getchar to read single characters from the “standard
input,'' and putchar to write single characters to the standard output.
“Standard input'' and “standard output'' are two predefined I/O streams
which are implicitly available to us.
stdin is a constant file pointer corresponding to standard input, and stdout is
a constant file pointer corresponding to standard output. Both of these can
be used anywhere a file pointer is called for; for example, getchar() is the
same as getc(stdin) and putchar(c) is the same as putc(c, stdout). The third
predefined stream is stderr. Like stdout, stderr is typically connected to the
screen by default. The difference is that stderr is not redirected when the
standard output is redirected. For example, under Unix or MS-DOS, when
we invoke
program > filename

Sikkim Manipal University B2074 Page No.: 308


Principles of C Programming Unit 14

anything printed to stdout is redirected to the file filename, but anything


printed to stderr still goes to the screen. The intention behind stderr is that it
is the “standard error output'' and error messages printed to it will not
disappear into an output file. For example, a more realistic way to print an
error message when a file cannot be opened would be
if((ifp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "can't open file %s\n", filename);
exit or return
}
where filename is a string variable indicating the file name to be opened.
Not only is the error message printed to stderr, but it is also more
informative in that it mentions the name of the file that could not be opened.
Self Assessment Questions
5. stderr can be redirected to file. (True/False)
6. __________ is a constant file pointer corresponding to standard input.
7. getchar() is the same as getc(stdin). (True/False)

14.5 Error Handling during I/O operations


The standard I/O functions maintain two indicators with each open stream to
show the end-of-file and error status of the stream. These can be
interrogated and set by the following functions:
#include <stdio.h>
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
void perror(const char *s);

clearerr clears the error and EOF indicators for the stream.
feof returns non-zero if the stream's EOF indicator is set, zero otherwise.
ferror returns non-zero if the stream's error indicator is set, zero otherwise.
perror prints a single-line error message on the program's standard output,
prefixed by the string pointed to by s, with a colon and a space appended.
The error message is determined by the value of errno and is intended to

Sikkim Manipal University B2074 Page No.: 309


Principles of C Programming Unit 14

give some explanation of the condition causing the error. For example, this
program produces the error message shown:

#include <stdio.h>
#include <stdlib.h>
main(){

fclose(stdout);
if(fgetc(stdout) >= 0){
fprintf(stderr, "What - no error!\n");
exit(EXIT_FAILURE);
}
perror("fgetc");
exit(EXIT_SUCCESS);
}

/* Result */
fgetc: Bad file number

Self Assessment Questions


8. __________ clears the error and EOF indicators for the stream.
9. __________ returns non-zero if the stream's error indicator is set, zero
otherwise.

14.6 Random Access to files


So far we have discussed how to read or write data sequentially to an
opened disk file, known as sequential access. In other words, we start with
the first byte and keep reading or writing each successive byte in order. In
many cases, however, we need to access particular data somewhere in the
middle of a disk file. One way to do it is to keep reading data from the file
until the particular data is fetched. This is not an efficient way, especially
when the file contains many data items. Random access is another way to
read or write data to disk files.
In random access, specific file elements can be accessed in random order
(or in other words without reading through all the preceding data). In the
section 14.2, we learned that one of the members in the FILE structure is
called the file position indicator. The file position indicator has to point to the

Sikkim Manipal University B2074 Page No.: 310


Principles of C Programming Unit 14

desired position in a file before data can be read from or written to it. The
Random Access functions allow control over the implied read/write position
in the file. The file position indicator is moved without the need for a read or
a write, and indicates the byte to be the subject of the next operation on the
file.
In C, three types of function exist which allow the file position indicator to be
examined or changed. Their declarations and descriptions follow.

#include <stdio.h>

/* return file position indicator */


long ftell(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);

/* set file position indicator to zero */


void rewind(FILE *stream);

/* set file position indicator */


int fseek(FILE *stream, long offset, int ptrname);
int fsetpos(FILE *stream, const fpos_t *pos);

ftell returns the current value (measured in characters) of the file position
indicator if stream refers to a binary file. For a text file, a ‘magic’ number is
returned, which may only be used on a subsequent call to fseek to
reposition to the current file position indicator. On failure, -1L is returned and
errno is set.
rewind sets the current file position indicator to the start of the file indicated
by stream. The file's error indicator is reset by a call of rewind. No value is
returned.
fseek allows the file position indicator for stream to be set to an arbitrary
value (for binary files), or for text files, only to a position obtained from ftell,
as follows:
 In the general case, the file position indicator is set to offset bytes
(characters) from a point in the file determined by the value of ptrname.
Offset may be negative. The values of ptrname may be SEEK_SET,
which sets the file position indicator relative to the beginning of the file,

Sikkim Manipal University B2074 Page No.: 311


Principles of C Programming Unit 14

SEEK_CUR, which sets the file position indicator relative to its current
value, and SEEK_END, which sets the file position indicator relative to
the end of the file. The latter is not necessarily guaranteed to work
properly on binary streams.
 For text files, offset must either be zero or a value returned from a
previous call to ftell for the same stream, and the value of ptrname must
be SEEK_SET.
 fseek clears the end of file indicator for the given stream and erases the
memory of any ungetc. It works for both input and output.
 Zero is returned for success, non-zero for a forbidden request.
Note that for ftell and fseek it must be possible to encode the value of the
file position indicator into a long. This may not work for very long files, so the
Standard introduces fgetpos and fsetpos which have been specified in a
way that it removes the problem.
fgetpos stores the current file position indicator for stream in the object
pointed to by pos. The value stored is ‘magic’ and only used to return to the
specified position for the same stream using fsetpos.
fsetpos works as described above, also clearing the stream's end-of-file
indicator and forgetting the effects of any ungetc operations.
For both functions, on success, zero is returned; on failure, non-zero is
returned and errno is set.
Self Assessment Questions
10. ____________ function returns the current value (measured in
characters) of the file position indicator if stream refers to a binary file.
11. fseek allows the file position indicator for stream to be set to an
arbitrary value. (True/False)
12. __________ stores the current file position indicator for stream in the
object pointed to by pos.

14.7 Command Line Arguments


We have mentioned several times that a program is rarely useful if it does
exactly the same thing every time it is run. Another way of giving a program
some variable input to work on is by invoking it with command line

Sikkim Manipal University B2074 Page No.: 312


Principles of C Programming Unit 14

arguments. It is a parameter supplied to a program when the program is


invoked.
We should probably admit that command line user interfaces are a bit old-
fashioned, and currently somewhat out of favor. If we have used Unix or
MS-DOS, we know what a command line is, but if experience is confined to
the Macintosh or Microsoft Windows or some other Graphical User Interface,
we may never have seen a command line.
C's model of the command line is that it consists of a sequence of words,
typically separated by whitespace. Our main program can receive these
words as an array of strings, one word per string. In fact, the C run-time
startup code is always willing to pass this array, and all we have to do to
receive it is to declare main as accepting two parameters, like this:
int main(int argc, char *argv[])
{
...
}
When main is called, argc will be a count of the number of command-line
arguments, and argv will be an array (“vector'') of the arguments themselves.
Since each word is a string which is represented as a pointer-to-char, argv
is an array-of-pointers-to-char. Since we are not defining the argv array, but
merely declaring a parameter which references an array somewhere else
(namely, in main's caller, the run-time startup code), we do not have to
supply an array dimension for argv. Actually, since functions never receive
arrays as parameters in C, argv can also be thought of as a pointer-to-
pointer-to-char, or char **. But multidimensional arrays and pointers to
pointers can be confusing, and we have not covered them, so we will talk
about argv as if it were an array. Also, there is nothing magical about the
names argc and argv. We can give main's two parameters any names we
like, as long as they have the appropriate types. The names argc and argv
are traditionally used.
The first program to write when playing with argc and argv is one which
simply prints its arguments:

Sikkim Manipal University B2074 Page No.: 313


Principles of C Programming Unit 14

Program 14.3: To illustrate the use of command line arguments


#include <stdio.h>
main(int argc, char *argv[])
{
int i;

for(i = 0; i < argc; i++)


printf("arg %d: %s\n", i, argv[i]);
return 0;
}

(This program is essentially the Unix or MS-DOS echo command.)


If we run this program, we will discover that the set of “words” making up the
command line includes the command we typed to invoke our program that is,
the name of program. In other words, argv[0] typically points to the name of
program, and argv[1] is the first argument.
There are no hard-and-fast rules for how a program should interpret its
command line. There is one set of conventions for Unix, another for MS-
DOS and another for VMS. Typically, we will loop over the arguments,
perhaps treating some as option flags and others as actual arguments (input
files, and so on.) interpreting or acting on each one. Since each argument is
a string, we have to use strcmp or the like to match arguments against any
patterns we might be looking for. Remember that argc contains the number
of words on the command line, and that argv[0] is the command name, so if
argc is 1, there are no arguments to inspect. (We never want to look at
argv[i], for i >= argc, because it will be a null or invalid pointer.)
A further example of the use of argc and argv now follows:

Program 14.4: To illustrate the use of command line arguments


void main(int argc, char *argv[])
{
if (argc !=2) {
printf("Specify a password");
exit(1);
}
if (!strcmp(argv[1], "password"))
Sikkim Manipal University B2074 Page No.: 314
Principles of C Programming Unit 14

printf("Access Permitted");
else
{
printf("Access denied");
exit(1);
}
program code here ......
}

This program only allows access to its code if the correct password is
entered as a command-line argument. There are many uses for command-
line arguments and they can be a powerful tool.
As another example, here is a program which searches character from the
input file and if the character is available in the file, displays the message
found and comes out from the loop.
Program 14.5: Program to search the specified file, looking for the
character
/*Search specified file for specified character. */
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
FILE *fp; /* file pointer */
char ch;

/* see if correct number of command line arguments */


if(argc !=3) {
printf("Usage: find <filename> <ch>\n");
exit(1);
}

/* open file for input */


if ((fp = fopen(argv[1], "r"))==NULL) {
printf("Cannot open file \n");
exit(1);
}

Sikkim Manipal University B2074 Page No.: 315


Principles of C Programming Unit 14

/* look for character */


while ((ch = fgetc(fp)) !=EOF) /* where fgetc() is a */
if (ch== *argv[2]) { /*function to get one char*/
printf("%c found",ch); /* from the file */
break;
}
fclose(fp);
}

Self Assessment Questions


13. Command line argument is a parameter supplied to a program when
the program is invoked. (True/False)
14. In the command line arguments of main(), argv is an array-of-pointers-
to-___________.
15. The ____________ is a parameter supplied to a program when the
program is invoked.

14.8 Summary
Let us recapitulate important points discussed in this unit:
 In C, a file can refer to a disk file, a terminal, a printer, or a tape drive.
 A stream is a series of ordered bytes. Unlike a file, a stream is device
independent. There are two stream formats: text stream and binary
stream.
 The file position indicator in the FILE structure points to the position in a
file where data will next be read from or written to.
 The fopen() function is used to open a file and associate a stream to the
opened file. We can specify different modes for opening a file.
 The fclose() function is responsible for closing an opened file and
disassociating a stream with the file.
 The fgetc() and fputc() functions read or write one character at a time.
 The fgets() and fputs() functions read or write one line at a time.
 The fprintf() and fscanf() functions for formatted I/O file operation.
 The feof() function can determine when the end of a file has been
reached.
 “Standard input'' and “standard output'' are two predefined I/O streams
which are implicitly available to us.
Sikkim Manipal University B2074 Page No.: 316
Principles of C Programming Unit 14

 The Random Access functions allow control over the implied read/write
position in the file.
 The command line argument is a parameter supplied to a program when
the program is invoked.

14.9 Terminal Questions


1. What is meant by opening a file? How is this accomplished?
2. Describe the use of functions fgetc() and putc().
3. Explain the general syntax of the fseek() function.
4. What is a command line argument and what is its use? Explain

14.10 Answers
Self Assessment Questions
1. stdio.h
2. null pointer
3. File pointer
4. True
5. false
6. stdin
7. True
8. clearerr
9. ferror
10. ftell
11. true
12. fgetpos
13. true
14. char
15. Command line argument

Answers to Terminal Questions


1. The C I/O function fopen() opens a file and associates a stream with the
opened file. (Refer section 14.2 for more details)
2. Among the C I/O functions, there is a pair of functions, fgetc() and fputc(),
that can be used to read from or write to a disk file one character at a
time. (Refer section 14.4.1 for more details)
3. The syntax for the fseek() is :
Sikkim Manipal University B2074 Page No.: 317
Principles of C Programming Unit 14

/* set file position indicator */


int fseek(FILE *stream, long offset, int ptrname);
(Refer section 14.6 for more details)
4. Command Line argument is a parameter supplied to a program when
the program is invoked. (Refer section 14.7 for more details)

14.11 Exercises
1. Distinguish between the following functions:
a) getc and getchar
b) printf and fprintf
c) feof and ferror
2. Write a program to copy the contents of one file to another.
3. Two data files DATA1 and DATA2 contains sorted list of integers. Write
a program to produce a third file DATA which holds the single sorted,
merged list of these two lists. Use command line arguments to specify
the file names.
4. The skeletal outline of an C program is shown below.
#include <stdio.h>
main()
{
FILE *pt1, *pt2;
int a;
float b;
char c;
pt1 = fopen(“sample.old”, “r”);
pt2= fopen (“sample.new”,”w”);
……..

fclose(pt1);
fclose(pt2);
}
Identify and Write file function required to perform following:
a) Read the values of a, b and c from the data file sample.old.
b) Display each value on the screen and enter an updated value.

Sikkim Manipal University B2074 Page No.: 318


Principles of C Programming Unit 14

c) Write the new values to the data file sample.new. Format the floating-
point value so that not more than two decimals are written to
sample.new.

__________________

Sikkim Manipal University B2074 Page No.: 319

You might also like