Unit 5 Files For Civil
Unit 5 Files For Civil
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.
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.
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.
File handling functions in ‘C’ library / file management or manipulation functions in C (or)
File operations in C
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.
Both ‘file name’ and ‘mode’ are specified as string they should be enclosed in ‘’ ‘’.
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(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
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
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
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
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.
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
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.
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.
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
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.
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);
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);
}
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);
Ex: int x;
x = getw (fp);
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);
}
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();
}
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.
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);
0 beginning of file
1 current position
2 end of file
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;
if(fp= =NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
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