0% found this document useful (0 votes)
21 views8 pages

FILES

The document discusses file input/output (I/O) in C programming. It covers defining and opening files, closing files, reading from and writing to files, and additional file I/O functions. Key points include: 1) To work with files in C, a file must first be declared as type FILE and opened using fopen(). This returns a file pointer used for other file functions. 2) Files can be opened for reading, writing, or appending using flags like "r", "w", and "a". 3) The fclose() function closes the file and cleans up resources. 4) Common file I/O functions include fprintf() to write and f

Uploaded by

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

FILES

The document discusses file input/output (I/O) in C programming. It covers defining and opening files, closing files, reading from and writing to files, and additional file I/O functions. Key points include: 1) To work with files in C, a file must first be declared as type FILE and opened using fopen(). This returns a file pointer used for other file functions. 2) Files can be opened for reading, writing, or appending using flags like "r", "w", and "a". 3) The fclose() function closes the file and cleans up resources. 4) Common file I/O functions include fprintf() to write and f

Uploaded by

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

I.

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:

I.1- Defining and opening the file


[See Activity 8.4]

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”);

Mode can be one of the following:

 “r” open the file for reading only.


 “w” open the file for writing only.
 “a” open the file for appending(or adding)data to it.

The additional modes of operation are:

 “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);

I.3- Reading and writing on a file [See


Activity 8.5]

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.

fprintf(fp,"%s","This is just an example :)");

I.4- Additional File I/O Functions


Many of the specialized I/O functions for characters and strings that we have described in this
course have analogs which can be used for file I/O. Here is a list of these functions
Function Result

fgets file string input

fputs file string output


getc(fp) file character input

putc(fp) file character output

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");

I.4- Additional File I/O Functions


The following program read the file union.cpp which should be in the same folder than the
source code, append it and display it on the screen.
#include <stdio.h>

main( )

FILE *fp;

char c;

fp = fopen("union.cpp", "a");

if (fp == NULL)

printf("File doesn't exist\n");

else {

fprintf(fp,"%s","This is just an example :)"); /*append some text*/

fclose(fp);

fp = fopen("union.cpp", "r");
do {

c = getc(fp); /* get one character from the file */

putchar(c); /* display it on the monitor*/

} while (c != EOF); /* repeat until EOF (end of file) */

fclose(fp);

getchar();

EXERCISE 8

Exercise 8.1: Let’s consider the following structure declaration


Struct fraction
{
Int num;
Int dem;
};
Write functions enabling to do the following manipulations on fractions
a) Add two fractions
b) Multiply two fractions
c) Divide two fractions

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.

Exercise 8.3: A complex number can be defined by the following structure

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

Exercise 8.4: Let’s consider the following structure

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:

- An array of structure should be used to store information of a maximum of 20 students


- The number of students to record and the information should be entered by the user
- The grade should be assigned by a function according to the following table

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

read character from file


while not end of file and not finished do
begin
display character
if character is newline then
linecount = linecount + 1;
if linecount == 20 then
begin
linecount = 1 ;
Prompt user and get reply;
end
read next character from file
end

Exercise 8.9: Write a file copy program which copies the file “prog.c” to “prog.old”

Outline solution:

Open files appropriately


Check open succeeded
Read characters from prog.c and
Write characters to prog.old until all characters copied
Close files

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:

read character ca from file A;


read character cb from file B;
while ca == cb and not EOF file A and not EOF file B
begin
read character ca from file A;
read character cb from file B;
end
if ca == cb then
printout(“Files identical”);
else
printout(“Files differ”);

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,

You might also like