FILES
FILES
FILES
So far, all the output (formatted or not) in this course has been written out to what is called
standard output (which is usually the monitor). Similarly all input has come from standard input
(usually associated with the keyboard).
The C programmer can also read data directly from files and write directly to files. To work with
files, the following steps must be taken:
Data structure of a file is defined as FILE in the library of standard I/O function definitions.
Therefore all files should be declared as type FILE before they are used. FILE is a defined data
type. Constants such as FILE, EOF and NULL are defined in <stdio.h>. The following is the
general format for declaring and opening a file:
FILE *fp;
fp = fopen(“filename”, “mode”);
“r+” the existing file is opened to the beginning for both reading and writing.
“w+” same as w except both for reading and writing.
“a+” same as a except both for reading and writing.
The following useful table lists the different actions and requirements of the different modes for
opening a file:
I.2- Closing a file
The fclose function in a sense does the opposite of what the fopen does: it tells the system that
we no longer need access to the file. This allows the operating system to cleanup any resources
or buffers associated with the file.
The syntax for file closing is simply
fclose(in_file);
The functions fprintf and fscanf are provided by C to perform the analogous operations for the
printf and scanf functions but on a file.
Opening a file for reading requires that the file already exist. If it does not exist, the file pointer
will be set to NULL and can be checked by the program.
fscanf(fp,"%f %d",&x,&m);
When a file is opened for writing, it will be created if it does not already exist and it will be reset
if it does, resulting in the deletion of any data already there. Using the w indicates that the file is
assumed to be a text file.
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar() and putc(c,fp) is similar to putchar(c).
Thus the statement c = getc(fp); reads the next character from the file referenced by fp and the
statement putc(c,fp); writes the character c into file referenced by fp.
Another useful function for file I/O is feof() which tests for the end-of-file condition. feof takes
one argument -- the FILE pointer -- and returns a nonzero integer value (TRUE) if an attempt has
been made to read past the end of a file. It returns zero (FALSE) otherwise. A sample use:
if (feof(fp))
printf ("No more data \n");
main( )
FILE *fp;
char c;
fp = fopen("union.cpp", "a");
if (fp == NULL)
else {
fclose(fp);
fp = fopen("union.cpp", "r");
do {
fclose(fp);
getchar();
EXERCISE 8
Exercise 8.2: Create a structure called car with the following members:
• make
• model
• year
• miles
a) Create an instance of the car structure named myCar and assign data to each of the
members. Print the contents of each member to standard output using the printf()
function.
b) Using the car structure from challenge number one, create a structure array with three
elements named myCars. Populate each structure in the array with your favorite car
model information. Use a for loop to print each structure detail in the array.
struct comp
{
double real;
double imag;
};
Use the following prototypes to write the corresponding function
a) void printcomp(struct comp a); to print a complex number in the form x+yi
b) int mod(struct comp a); To calculate the modulus of a given complex number a
c) int compare(struct comp a, struct comp b); to compare two complex numbers
d) struct comp add(struct comp a, struct comp b); to add two complex numbers
e) struct comp add(struct comp a, struct comp b); to multiply two complex numbers
Write a main program to use these functions. A menu should be displayed to enable the user choosing
the operation he wants to perform
Struct point
{
Float x;
Float y;
}
Write a function enable you to:
a) Calculate the distance between two points
b) Calculate the coordinate of vertor AB given 2 points A and B
c) Make a translation of a point by a vector
Exercise 8.5: Write a simple database program that will store students’ information such as name, age,
mark and grade. The following instructions should be followed:
mark grade
>= 80 A
<80 and >=60 B
<60 and >=40 C
<40 F
The write codes to perform the following
a) Calculate the mark average of all the student
b) Determine the first and the last student
c) Display the students who have passed knowing that a student has passed if he has at least 60/100
d) Given a student name display his details if the name exist in the database
Exercise 8.6: Let’s consider the following code fragment. It show how a program might check if a file
could be opened appropriately. The function exit() is a special function which terminates your program
immediately.
fp = fopen (filename, “r”) ;
if ( fp == NULL)
{
printf(“Cannot open %s for reading \n”, filename );
exit(1) ; /*Terminate program: Commit suicide !!*/
}
a) Modify the code so that the a valid name of file should be entered before the execution of
the program continue
b) Modify the above code fragment to allow the user 3 chances to enter a valid filename. If a
valid file name is not entered after 3 chances, terminate the program.
Exercise 8.7: Write a program to count the number of lines and characters in a file.
Note: Each line of input from a file or keyboard will be terminated by the newline character ‘\n’.
Thus by counting newlines we know how many lines there are in our input.
Exercise 8.8: Write a program to display file contents 20 lines at a time. The program pauses after
displaying 20 lines until the user presses either Q to quit or Return to display the next 20 lines. The
following algorithm can be used
Exercise 8.9: Write a file copy program which copies the file “prog.c” to “prog.old”
Outline solution:
The step: “Read characters .... and write ..” may be refined to:
read character from prog.c
while not end of file do
begin
write character to prog.old
read next character from prog.c
end
Exercise 8.10: The following simple structure declarations might be found in a graphics environment.
struct point
{
double x;
double y;
};
struct circle
{
double rad;
struct point cen;
};
With the declarations given above write simple C function to
a) Calculate the area of a circle
b) Determine whether a given point lay inside a circle
Exercise 8.11: Write a program to compare two files specified by the user, displaying a message
indicating whether the files are identical or different. This is the basis of a compare command provided
by most operating systems. Here our file processing loop is as follows:
Exercise 8.12: By using the structure point defined in exercise 4, consider the following
structure
struct line
{
struct point start;
struct point end;
};
Using the structure above, write a code to determine if two lines are
a) Parallel
b) Perpendicular
Exercise 8.13: Redo exercise 5 using a file to store the database. A menu should be prompted to
the user to choose the operation to do
a) Display the detail of the database
b) Add a record to the database
c) Give the number of records of the database
d) Calculate the mark average of all the student
Etc,