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

Unit 5 Files For Civil

Files in C can be accessed through standard library functions and contain records of related data items. There are two types of files - text files containing human-readable characters and binary files containing raw data. Common file I/O functions allow reading from and writing to files, including formatted functions like fprintf and fscanf, and unformatted functions. Proper file handling requires opening, reading/writing, and closing files using functions like fopen, getc, putc, and fclose.

Uploaded by

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

Unit 5 Files For Civil

Files in C can be accessed through standard library functions and contain records of related data items. There are two types of files - text files containing human-readable characters and binary files containing raw data. Common file I/O functions allow reading from and writing to files, including formatted functions like fprintf and fscanf, and unformatted functions. Proper file handling requires opening, reading/writing, and closing files using functions like fopen, getc, putc, and fclose.

Uploaded by

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

CPDS-VI

FILE MANAGEMENT IN C
FILES:
A File is a collection of records that can be accessed through the set of library functions.
Record is nothing but collection of fields of related data items. These files are stored on the
disk and can be accessed through file-handling functions provided by the C-standard library.

File I/O functions :-


Sometimes it is necessary to store the data in a manner that can be later retrieved and
displayed either in a part or in whole. This medium is usually a “file” on the disk.
File I/O can be handled by using different functions.

a) Formatted functions:- The file input function fscanf( ) and the file output function
fprintf( ) are called formatted file I/O functions.

b)Unformatted functions:- The input functions like getc( ), getw( ), and fread( ) are called
unformatted file input functions and putc( ), putw( ), and fwrite( ) functions are unformatted
file output functions. Each and every function is having its own syntax and meaning.

File streams:-
Stream is either reading or writing of data. The streams are designed to allow the user to
access the files efficiently.

Streams provide communication channels between files and programs. Three


files and their associated streams are automatically opened when program
execution begins:

 the standard input to read data from the keyboard (stdin)


 the standard output to print data on the screen. (stdout)
 the standard error (stderr).

Text files and Binary files:- C uses two types of files, text files and binary files.

Text files:- Text file is a file consists of a sequence of characters divided into lines with each
line terminated by a new line(‘\n’).
A text file is writing using text stream. We can read and write text files using different
input/output functions.
Formatted input/output (scanf/printf), character input/output (getchar/putchar), and string
input/output (gets/puts) functions. And these functions can work with only text files.
A text file contains only textual information like alphabets, digits, and special symbols. In
actuality the ASCII codes of these characters are stored in text files.
Ex: A good example of text file is any C program file.

mrit
CPDS-VI

Binary files:- A binary file is a collection of data stored in the internal format of the
computer. Unlike text files, the data do not need to be reformatted as they are read and
write rather, the data is stored in the file in the same format that they are stored in memory.
Binary files are read and write using binary streams known as block input/output functions.
Simply a binary file is merely a collection of bytes. This collection might be a compiled
version of a C program or music data stored in a wave file or a picture stored in a graphic file.

Differences between Text and Binary files:-


The major characteristics of text files are:
1. All data in a text file are human-readable graphic characters.
2. Each line of data ends with a newline character.
3. There is a special character called end-of-file(EOF) marker at the of the file.

The major characteristics of binary files are:


1. Data is stored in the same format as that is stored in memory.
2. There are no lines or new line characters.
3. There is an end-of-file marker.

The basic file operation in ‘C’


1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing file

There are two ways to perform file operations in „C‟.


1. The low-level I/O and uses UNIX system call.
2. The high-level I/O operation and uses „C‟ library.

File handling functions in ‘C’ library / file management or manipulation functions in C (or)
File operations in C

fopen( ) → creates a new life for use/open existing file


fclose( ) → closes file
getc( ) → read a char from file
putc( ) →writes a char to file
fprintf →writes a set of data values to a file
fscanf → reads a se of data values from a file
getw( ) → reads an integer from a file
putw( ) → writes an integer to a file
fseek( ) → sets the position to a designed point in file
ftell( ) → sets the position to the beginning of file

Explanation of above functions :

Fopen function: The general format for declaring and opening la file is

FILE *fp;
mrit
CPDS-VI
Fp = fopen ( “file name”, “mode” );

Where the variable fp has a pointer to the data type File opens the File
name a and pointer assigns an identifier to the File type pointer fp. This pointer
which contains all the information about the File subsequently used as a
communication link between the system used as a communication between the
system and the program.

“Mode” can be one the following

r - open the file for reading only.


w - open the file writing only.
a - open the file for appending (adding) data to each.

Both ‘file name’ and ‘mode’ are specified as string they should be enclosed in ‘’ ‘’.

Ex : FILE * fp1, *fp2;


Fp1 = fopen (“data’’, “r”);
Fp2= fopen (“result”, “w”);

Where fp1,fp2 are pointer the ‘fp1’ is opens the File named as data for
reading mode only then fp2 opens the file named as ‘result for writing made only

Fclose function : A File must be closed after all operations have been completed.
The general form of fclose function is

Fclose (file pointer);

Ex : Fp1 =fopen (“input”, "W”);


Fp2 = fopen(“output”, “r”);

Fclose(fp1);
Fclose(fp2);

This program opens two files and closes them after all operations on them are
completed once a file is closed its file pointer can be reused for another file.

The getc function : It is used to read a character from a file that has been opened
in read mode the general form of statement is

C=getc (file pointer);

Here read a character from the file whose pointer is file pointer and assigned
the reading character to ‘C’. The reading is terminated when getc encounter end of
file mark Eof.

Ex : File *fp;
Char c;

mrit
CPDS-VI

Fp=fopen (“input”, “r”);


While(c=getc(fp)!=Eof)
Putchar ( c );

The putc function : The another simple I/o function is putc. putc is used to write a
character to a file that has been opened in write mode.

Putc (c,fp);

Where read a character through to the variable and put these character
through whose file pointer is fp the writing is terminated when putc encounters the
end of file mark EOF.

Ex : FILE *fp;
Char C;
Fp=fopen(“input”, “w”);
While (c = getchar( c )!= EOF)
Putc(c, fp);
The getw function : The simplest integer oriented file I/o function is get w that
has been opened in read mode the general from of statement is

Num =getw (fp);

Where read an integer value from the file whose file pointer is fp and
assigned the reading numbers to num. The reading is terminated when getw
encounters the end of file mark EOF.

Ex : FILE *fp
Int num;
Fp=fopen (“input”, "r”);
While (num=getw(fp)!=EOF)
Printf(“%d”, num);

The Putw function : The simplest I/O integer oriented function is putw. ‘putw’ is
used to create an integer value to a file that has been opened in write mode. The
general form statement is

Putw(num,fp);

Where read a number through to the variable ‘num’ and put the number into
the file whose file pointer is fp. The waiting is terminted when ‘Putw’ encounters the
end of file mark Eof (i.e,num=0)

Ex : FILE *fp
Int num;
Fp=fopen (“INPUT”, "w”);
Scanf(“%d”, & num);
While (num!= fp)
Putw(num,fp);
Scanf(“%d”, & num);

mrit
CPDS-VI
The fprintf function : The fprintf statement is used to write data items to the file
whose file pointer is opened in the writing mode. ‘fprintf’ perform I/O operations an
files the general form of fprintf is

Fprintf (fp, "control string", list);

Where ‘fp’ is a file pointer associated with a file that has been opened for
writing. The control string contains output specifications for the items in the list. The
list may be including variable constants and strings.

Ex : fprintf (fp1, "%s %d %f”, name age,7.5);

Where ‘name is an array variable of type and age is an int variable.

The fscanf function : The fscanf function is used to read data items to the file
whose pointer is opened in the reading mode. fscanf function performs I/O
operations on files. The general form of fscanf is

fscanf (fp, “control string”, list);

This statement reading of the items in the list from the file specified by fp. The
control string contains input specifications for the items in the list.

Ex : fscanf (fp1, “%s %d”, item & quantity

Where “item “ is an array variable of type and quanity is an int variable.


Fscanf returns the no.of items when the end of file is reached 'i' returns the value Eof

The feof function : This function can be used to test for an end of file condition It
takes a file pointer as an argument and returns a non-zero integer value id all of the
data from the specified file has been read and returns zero otherwise.

If (feof (fp)
Printf(“end of file”);

This statement gives the end of data when encountered end of file condition

The ferror function : It is also takes a file pointer its argument and returns a non-
zero integer if an error has been detected upto that point during processing it returns
zero otherwise.

Ex : The statement If (ferror (fp)!=0)


Printf(“file could not be open”);

Print the error message if the reading is not successful.

The ftell function : This function is useful in saving the current position of a file,
which can be used later in the program . It takes the following form

N = ftell ( fp);

Where ‘n’ gives the relative offset (in bytes) of the current position. This
means that ‘n’ bytes have already read.

mrit
CPDS-VI
The Rewind function : It takes a file pointer and resets the position to the start of
the (in bytes). The statement is

Rewind (fp);
N = ftell(fp);

It will assign ‘o’ to n’ because the file position has been set to the start of the
file by rewinded. i.e.., The first byte in the file is numbered as ‘o’ second as ‘1’ and a
so on.

Fseek function : It is used to move the file position to a desired location within the
file It takes the following form

Fseek (file pointer, offset, position);

Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or variable of type
‘long’, and position is an integer variable. The offset specifies the positions (bytes) to
be moved from the location specified by position.

Defining and opening a file:


If we want to store data in a file in secondary memory, we must specify about
the file information to the operating system.
→ File name (string of chars, it may contain two parts)
→ Data structure (structure is defined as FILE in the library of I/O )
→ Purpose (what we want to do with the file we may read /write data)

Valid file names


a. input.data
b. Student.c
c. Text.out

All files should be declared as type FILE before used.

The general format for declaring and Opening file


FILE *fp;
fp = fopen(“filename”, “mode”);
Example :
FILE *fp;
fp = fopen(“input.data”, “w”);

Here, fp is a variable of pointer to the data type FILE. Fopen is used to open Input.data file
and assigns an identifier to the FILE type pointer fp. This pointer contains all the information
About file and used as a common link between the system and program “w” is mode (write)
of opening a file.
 r →opens file for reading only
 w → opens file for writing only
 a → opens file for appending (adding)data.

mrit
CPDS-VI
 r+ → for both reading and writing at the beginning only
 w+ → after writing we may read the file without closing and reopening
 a+ → open a file in read and append mode

A. When the mode is writing new file is created (or) the contents are deleted, if the file
is already existed.
B. When the mode is appending, the file is opened and add the contents of new (or)
new file also created, if file does not exist.
C. When the mode is reading, if the file existed then the file is opened with the current
contents safe otherwise an error occurs.

Closing a File:
A file must be closed as soon as all operations on it have been completed. This ensures all
the information flushed out from the buffers and all links to the file are broken.
Syntax: fclose(filepointer);
Example: fclose(fp);

Input/output operations on Files:


getc and putc functions: the simplest file I/o functions are getc and putc.
getc ( ): getting a character from the file, or reading the file information character by
character at a time, upto the end of the file by using this function.

Ex: char ch;


ch = getc (fp);

putc ( ):-Putting a character in to the file. It works with only character data type. One
character at a time can write into a file.
Ex: char ch =’a’;
putc (ch, fp);

EOF – End of file (when EOF encountered the reading / writing should be terminated)

Program: WAP to read data from the keyboard and write it to a file, gain read same data
from file, display on the screen.
main ( )
{
FILE *fp1;
char c;
clrscr( );
fp1 = fopen (“input.data”, “w”);
while ((c=getchar( ) )!=EOF)
putc (c,fp1);
fclose(fp1);
fp1 = fopen (“Input.data”, “r”);
while ((c=getc (fp1))! = EOF)
printf(“%c”,C);
fclose(fp1);
}

The getw and putw functions:

mrit
CPDS-VI
These are integer oriented functions. These are similar to above functions and are used to
read and write integer values. These are useful when we deal with only integer data. The
general format is
putw ( ): putting or writing of an integer value to a file.
putw (integer , fp);
Ex: int x = 5;
putw(x,fp);

getw ( ): getting or reading integer value from a file.

Ex: int x;
x = getw (fp);

The fprintf and fscanf functions:


Until now, we handle one char/integer at a time. But these functions handle a group of mixed
data simultaneously.
Syntax of fprintf is
fprintf (fp, “control string”, list);
Example: fprintf(fp1, “%s %d”, name, age);
Syntax of fscanf is,
fscanf(fp, “control string”, list);
Example: fscanf(fp, “%s %d”, name, & age);

 fscanf is used to read list of items from a file


 fprintf is used to write a list of items to a file.

Program: WAP to open a file named student and store the data of student name, age, marks.
And extended this program read data from this file and display the file on the screen with
total marks.

#include <stdio.h>
main ( )
{
FILE *fp1;
int age, marks, I total =0;
char name [10];
printf( “enter file name”);
scanf (“%s”, filename);
fp1 = fopen (filename, “w”);
printf( “input student data”);
for (i=1; i<=3; i++)
{
fscaf(stdin, “%s %d %d”, name, & age, & marks);
fprintf(fp, , “%s %d %d”, name, age, marks)‟
}
fclose(fp1);
fp=fopen(filename, “r”);
printf(“student name, age, marks, total”);
for (i=1; i<=3;I++)
{
fscanf(fp, “%s %d %d”, name, & age, & marks);
total = total + marks;
mrit
CPDS-VI
fprintf(stdout, “%s %d %d%d”, name, age, marks, total);
}
Fclose(fp);
}

/* PROGRAM TO COPY ONE FILE INTO ANOTHER FILE */


#include <stdio.h>
void main()
{
FILE *fs,*ft;
char ch;
clrscr();
fs=fopen("sample.txt","r");
if (fs==NULL)
{
puts("cannot open source file\n");
exit(1);
}
ft=fopen("sample1.txt","w");
if (ft==NULL)
{
puts("cannot open target file");
exit(1);
}
while((ch=fgetc(fs))!=EOF)
fputc(ch,ft);
fclose(fs);
fclose(ft);
getch();
}

/* EXAMPLE PROGRAM FOR ACCESSING BINARY FILES USING fwrite( ) ,


fread( )
FUNCTIONS */
#include<stdio.h>
void main()
{
int i,n;
FILE *fp1,*fp2,*fp3;
struct employ
{
char name[20];
int eno;
int bsal;
};
struct employ e[3];

mrit
CPDS-VI
clrscr();
fp1=fopen("EMP.DAT","wb");
for(i=0;i<3;i++)
{
printf("\n Enter name, num, and basic pay \n");
scanf("%s%d%d",e[i].name,&e[i].eno,e[i].bsal);
}
fwrite(&e,sizeof(e),3,fp1);
fclose(fp1);
fp1=fopen("EMP.DAT","rb");
fread(&e,sizeof(e),3,fp1);
for(i=0;i<3;i++)
{
printf("\n Name :%s",e[i].name);
printf("\n Number :%s",e[i].eno);
printf("\n basic pay :%s",e[i].bsal);
}
fclose(fp1);
getch();
}

Error handling during I/O operations (or) file status functions :-


There are 2 file errors 1) feof and 2) ferror
It is possible that an error may occur during I/O operations on a file. Typical errors situations
are:
 Trying to read beyond the end-of-file mark.
 Trying to perform an operation on a file, when the file is opened for another type of
operation.
 Device overflow
 Trying to use a file that has not been opened.
 Opening a file with an invalid file name.

Because of some above reasons a program may behave abnormally when an error Occurs. An
unchecked error may leads to incorrect output. C language supports two functions to check
such type of errors. Those are:
 feof( )
 ferror( )

feof( ):- This function can be used to test for an end of file condition. It takes one argument
as its FILE pointer and returns a nonzero integer value if all of the data from the specified file
has been read and returns zero otherwise.
Eg: if ( feof (fp) )
printf(“end of data”);
It will display the message “end of data” on reaching the end of file

mrit
CPDS-VI
ferror( ):- The ferror function reports the status of the file indicated. It also takes a FILE
pointer as its argument and returns a nonzero integer if an error has been detected up to that
point, during processing. It returns zero otherwise.
Eg: if ( ferror (fp) != 0)
printf(“An error has occurred”);
It will print the error message, if the reading is not successful.

/* EXAMPLE TO ILLUSTRATE ERROR HANDLING IN FILE OPERATIONS */


#include<stdio.h>
void main()
{
char *filename;
FILE *f1,*f2;
int i,n;
printf("\n enter filename to be open");
scanf("%s", filename);
f1=fopen(filename,"w");
for(i=10;i<=100;i+=10)
{
putw(i,f1);
}
fclose(f1);
f1=fopen(filename,"r");
for(i=1;i<=20;i++)
{
n=getw(f1);
if(feof(f1))
{
printf("\n file out of bounds");
break;
}
else
printf("\n %d",n);
}
fclose(f1);
getch();
}

Random Access to Files (or) Positioning functions in C:-


Files can be accessed either sequentially or randomly. Random accessing of files can be
achieved by using some predefined C library functions:
fseek( ),
ftell( ),
and rewind( ).

mrit
CPDS-VI
ftell( ) function:- If we wish to know where the file pointer is positioned right now, we can
use the function ftell. ftell takes a file pointer as an argument, and it returns the position as
long int which is an offset from the beginning of the file. It takes the following form:
syntax: n = ftell(fp);
n would give the relative offset(in bytes).

rewind( ):- This function places the file pointer to the beginning of the file, irrespective of
where it is present right now. It takes file pointer as an argument.
Syntax: rewind( fp);

fseek( ) function:- The fseek( ) function lets us move the pointer from one record to another.
Simply it is to move the file pointer to the desired location within a file. When the operation
is successful, fseek returns a zero. If we attempt to move the file pointer beyond the file
boundaries, an error occurs and fseek returns -1. It takes the following form:
syntax: fseek(file pointer, offset, position);

 file pointer is a pointer to the concerned file.


 Offset is a number or variable of type long, it specifies the number of positions (bytes)
to be moved from the location specified. If offset is positive number, then moving
forward or negative meaning move backwards.
 Position is a n integer number and it specifies from which position the file pointer to
be moved. Position can take one of the following three values.

0 beginning of file
1 current position
2 end of file

/* PROGRAM TO ACCESS A FILE RANDOMLY */


#include<stdio.h>
void main()
{
FILE *fp;
long n;
char c;
clrscr();
fp = fopen("sample.txt", "w+"); // opened for both writing and reading
while((c=getchar())!=EOF) // press CTRL+Z after entering the text
{
putc(c,fp);
}
n=ftell(fp); // stores the present location of file pointer in n
printf("\n No.of characters entered = %ld \n", n);
n=0L;
while(!feof(fp))
{
fseek(fp,n,0); // moves file pointer to the beginning of the file.
c=getc(fp);
putchar(c);
mrit
CPDS-VI
n=n+5L;
}
putchar('\n');
getch();
}

FILE PROGRAMS:

1) open a file
2) read a file
3) write a file
4) copy the files
5) delete a file
6) merge files

Open a file:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
main()
{
char ch,file_name[25];
FILE *fp;
clrscr();
printf("Enter the name of file you wish to see ");
gets(file_name);
fp=fopen(file_name,"r"); // read mode
if(fp= =NULL )
{
printf("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :- \n\n", file_name);
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
getch();
}

Output:
Enter the name of file you wish to see
wel.c
#include<stdio.h>
Main()
{
Printf(“welcome to c”);
}

Read a file:
#include<stdio.h>
#include<stdlib.h>

main()
{
mrit
CPDS-VI
char ch,file_name[25];
FILE *fp;

printf("Enter the name of file you wish to see ");


gets(file_name);

fp=fopen(file_name,"r"); // read mode

if(fp= =NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}

printf("The contents of %s file are :- \n\n", file_name);

while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
return 0;
}
Output:
Enter the name of file you wish to see
wel.c
#include<stdio.h>
Main()
{
Printf(“welcome to c”);
}

Write a file:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
FILE *fp;
char a[50];
fp = fopen("wel.c","w");
if(fp= =NULL)
{
puts("cant get me");
exit(0);
}
printf("\nEnter new line...\n");
while(strlen(gets(a))>0)
{
fputs(a,fp);
}
fclose(fp);
}
Output:
nEnter new line...

mrit
CPDS-VI
#include<stdio.h>
Main()
{
Printf(“welcome to c”);
}

Copy a file:
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
main()
{
char ch, source_file[20], target_file[20];
FILE *source, *target;
clrscr();
printf("Enter name of file to copy\n");
gets(source_file);
source=fopen(source_file, "r");
if(source= =NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
printf("Enter name of target file\n");
gets(target_file);
target=fopen(target_file, "w");
if( target = = NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while((ch=fgetc(source))!=EOF)
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
fclose(target);
getch();
}

Output:
Enter name of file to copy
2.c
Enter name of target file
Copy.c
File copied successfully.

Delete a file:
#include<stdio.h>
#include<conio.h>
main()
{
int status;

mrit
CPDS-VI
char file_name[25];
clrscr();
printf("Enter the name of file you wish to delete\n");
gets(file_name);
status = remove(file_name);
if( status = = 0 )
printf("%s file deleted successfully.\n",file_name);
else
{
printf("Unable to delete the file\n");
perror("Error");
}
getch();
}

Output:
Enter the name of file you wish to delete
2.c
2.c file deleted successfully.
merge a files:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
clrscr();
printf("Enter name of first file ");
gets(file1);
printf("Enter name of second file ");
gets(file2);
printf("Enter name of file which will store contents of two files ");
gets(file3);
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
if( fs1 = = NULL || fs2 = = NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}

ft=fopen(file3,"w");
if(ft= =NULL)
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while((ch=fgetc(fs1))!=EOF)
mrit
CPDS-VI
fputc(ch,ft);
while((ch=fgetc(fs2))!=EOF)
fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
getch();
}

Output:
Enter name of first file 2.c
Enter name of second file 3.c
Enter name of file which will store contents of two files merge.c
Two files were merged into %s file successfully.
Write a C program to count the lines, words and characters in a given text.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
int main( )
{
char ch;
int line=0, space=0, ct=0;
clrscr( );
printf("Enter the required no. of lines:\n");
while((ch=getchar( ))!=EOF)
{
if(ch==10)
{
line++;
}
if(isspace(ch))
{
space++;
}
ct++;
}
printf("\nNumber of Lines : %d", line+1);
printf("\nNumber of Words: %d", space+1);
printf("\nTotal Number of Characters: %d", ct);
getch( );
return 0;
}
Output:
Enter the required no. of lines:
We are hits students
Number of Lines :1
Number of Words:4
Total Number of Characters:20

mrit

You might also like