Unit5 231CSC201T
Unit5 231CSC201T
UNIT 5
Introduction – Using files in C - File operation: Read data from files, writing data to
files, detecting the end of file, Functions for selecting a record randomly – File pointer –
Error handling - Types of file processing: Sequential access, Random access- Dynamic
memory allocation.
FILES
Files are very important for storing information’s permanently. In other words files
are storage device which is used to store data permanently. File stores information for many
purposes and retrieve whenever required by our programs.
DEFINITION:
File is defined as a set of records containing numbers, symbols and text that can be
accessed through various file functions.
TYPES:
There are Many files which have their own type and own names. When we store a
file in the system, then we must specify the name and the type of file. The name of file will
be any valid name and type means the application with the file has linked. Based on this
we have two types:
1. Text File
2. Binary File
Text File:
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
Extension – “ filename.txt “
Binary File:
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better
security than text files.
Extension – “ filename.dat “
If you have to enter a large number of data, it will take a lot of time to enter them
all. However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
You can easily move your data from one computer to another without any changes.
Defining a file:
When accessing files through C, the first necessity is to have a way to access the files.
For C language we use a FILE pointer, which will let the program keep track of the file
being accessed.
Syntax: FILE *filepointer;
Example: FILE *fp;
This declaration is the communication between the file and the program. Here file is a
data structure; it has information about the file.
Opening a file:
Before we perform any operations on a file, we need to open it. We do this by using a
file pointer, then you use the function fopen() for opening a file.
Syntax : filepointer = fopen(“filename”.”mode”);
Example : fp = fopen(“cse.txt”,”r”);
Reading+ The new data is appended at the end Create new file
6 a+
Appending of file.
Closing a file:
A file must be close after completion of all operation related to the file. For closing
file we need to use the fclose() function.
Syntax: fclose(filepointer);
Example: fclose(fp);
Method 2 :
#include <stdio.h>
void main ()
{
char filename[50];
FILE *fp;
printf(“ enter the filename “);
gets(filename);
fp = fopen("filename", "r");
if (fp == NULL)
{
printf(" File does not exist ");
exit(0);
}
fclose(fp);
}
1.getc():
It is used to read a single character from both console screen and file at a time.Reads
the next character from the given input stream. getc() may be implemented as a macro.
Syntax: 1. variable=getc(stdin);
2. variable =getc(filepointer);
Example: 1. ch=getc(stdin);
2. ch=getc(fp);
EXAMPLE:
//Read content from file and display in console screen
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf((“\nContents from file are:”);
while((ch=getc(fp))!=EOF)
{
putchar(ch);
}
fclose(fp);
}
OUTPUT:
Contents from file are:Hello World
5
2.fgetc():
It is used to read the next character from the file. It is similar to getc() except it is
specific to file access.
Syntax: variable=fgetc(filepointer);
Example: ch=fgetc(fp);
EXAMPLE:
//Read content from file and display in console screen
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf((“\nContents from file are:”);
while((ch=fgetc(fp))!=EOF)
{
putchar(ch);
}
fclose(fp);
}
OUTPUT:
Contents from file are:Hello World
6
* It is used to read a single character from *It is used to read the next character from
both console screen and file at a time. the file. It is similar to getc() except it is
specific to file access.
*Reads the next character from the given * Reads the next character from the given
input stream. input stream
*Example: 1. ch=getc(stdin);
2. ch=getc(fp); *Example: ch=fgetc(fp);
3.putc():
putc() is used to write a single character to a file. It writes a character to the given
output stream. putc() may be implemented as a macro. It takes two arguments.
Syntax: putc(variable,filepointer);
Example: putc(ch,fp);
EXAMPLE:
//Read from screen and write in file.
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
7
{
printf(“Can’t open”);
exit(0);
}
printf((“\nEnter the text”);
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
}
OUTPUT:
Enter the text: Good Morning!!!
4.fputc():
This performs the same operation of putc() function. It writes a character to the
given output stream. But fputc() cannot be implemented as a macro. It takes one argument.
Syntax: fputc(variable,filepointer);
Example: fputc(ch,fp);
EXAMPLE:
//Read from screen and write in file.
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf((“\nEnter the text”);
8
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
fclose(fp);
}
OUTPUT:
Enter the text: Good Morning!!!
5.fgets():
fgets() is a file input statement which is used to read a string from the file. It takes
three arguments.
Syntax: fgets(stringvar,length,filepointer);
Here the stringvariable is the variable declared to hold a string. Length is the size of the
string.
Example: fgets(a,100,fp);
6.fputs:
fputs() is a file output statement that is used to write a string to the file. It takes two
arguments.
Syntax: fputs(stringvar,filepointer);
9
Example: fputs(a,fp);
OUTPUT:
“cse.txt”:
Computer Science and Engineering
Civil Engineering
Mechanical Engineering
“name.txt”:
Computer Science and Engineering
Civil Engineering
Mechanical Engineering
10
7. getw():
This is one of the file input/output functions. The getw() function is used to read an
integer from a file pointedby file pointer and assigns the value to the variable. It takes one
argument.
Syntax: variable=getw(filepointer);
Example: ch=getw(fp);
8. putw():
This is also one of file input/output functions. The putw() function is used towrite
an integer value into the file. It takes two arguments.
Syntax: putw(variable,filepointer);
Example: putw(ch,fp);
OUTPUT:
“cse.txt”:
1001
1005
1013
“regno.txt”:
1001
1005
1013
BINARY FILES:
1.fread():
This function is used to read upto count objects into the array buffer from the given
input stream (i.e.)it is used for reading an entire block from a given binary file. It is an
formatted read function.
Syntax: fread(&buffer_ptr,size,count,fileptr);
Example: fread(&s,n,2,fp);
2.fwrite():
The fwrite() function is used to write the objects in the given buffer to the output
stream (i.e.) it is used for writing an entire structure block to a binary file. It is an
unformatted write function.
Syntax: fwrite(&buffer_ptr,size,count,fileptr);
Example: fwrite(&s,n,1,fp);
EXAMPLE:
//Read from a binary file and copy it in another
#include<stdio.h>
#include<stdlib.h>
struct student
{
int rollno;
char name[20];
12
}
void main()
{
FILE *fp1,*fp2;
int i,n=5;
fp=fopen(“in.dat”,”rb”);
fp1=fopen(“out.dat”,”w”);
if(fp1==NULL||fp2==NULL)
{
printf(“Can’t open”);
exit(0);
}
for(i=0;i<n;i++)
{
fread(&s,sizeof(s),1,fp1);
}
for(i=0;i<n;i++)
{
fwrite(&s,sizeof(s),1,fp2);
}
fclose(fp1);
fclose(fp2);
}
OUTPUT:
“in.dat”:
1001 Abi
1002 Bharathi
“out.dat”:
1001 Abi
1005 Bharathi
1.fscanf():
This is a formatted file input function. This is used to read formatted data from the
given file. It takes three arguments.
13
Syntax: fscanf(filepointer,”controlstring”,&var1,&var2,……,&varn);
Example: fscanf(fp,”%d%s,&rollno,&name);
EXAMPLE:
//Read from file and display in console screen
#include<stdio.h>
#include<stdlib.h>
void main()
{
char name[20];
int rollno;
FILE *fp;
fp=fopen(“file.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf(“The contents are:”);
fscanf(fp,”%d%s”,&rollno,&name);
printf(“\n%d%s”,rollno,name);
fclose(fp);
}
OUTPUT:
The contents are: 1001 Raja
2.fprintf():
This function is used to write or print any formatted data to the file. fprintf() is a
formatted file output function. It takes three arguments.
Syntax: fprintf(filepointer,”controlstring”,var1,var2,……,varn);
Example: fprintf(fp,”%d%s,rollno,name);
EXAMPLE:
//Read from console and display in file
#include<stdio.h>
#include<stdlib.h>
void main()
14
{
char name[20];
int rollno;
FILE *fp;
fp=fopen(“file.txt”,”w”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf(“Enter rollno and name:”);
scanf(”%d%s”,&rollno,&name);
fprintf(fp“%d%s”,rollno,name);
fclose(fp);
}
OUTPUT:
Enter rollno and name: 1019 Bharathi
“file.txt”
1019 Bharathi
Description:
Sequential access files access the contents of the file in a sequential manner, (i.e.)
the file access pointer starts from the first character in the file and proceed until the last
character in the file (EOF).In order to access the nth character, all previous characters have
to be read and ignored. This method can be applicable for both text files and binary files.
The putc() and getc() functions are used to read and write a single character from text
files ,whereas read() and write() functions are used to read and write blocks of binary data.
# include<stdio.h>
#include<stdlib.h>
16
struct student
int roll_no;
char name[20];
int m1,m2,m3;
}s;
void main()
int i,n,key,ch,f;
FILE *fp;
scanf(“%d”,&n);
fp=fopen(“stud.dat”,”wb”);
if(fp==NULL)
exit(0);
for(i=0;i<n;i++)
printf(“enter rollno,name,m1,m2,m3:”);
scanf(“%d%s%d%d%d”,&s.roll_no,&s.name,&s.m1,&s.m2,&s.m3);
fwrite(&s,sizeof(s),1,fp);
17
fclose(fp);
while(1)
scanf(“%d”,&ch);
switch(ch)
case 1:fp=fopen(“stud.dat”,”rb”);
if(f1==NULL)
exit(0);
for(i=0;i<n;i++)
fread(&s,sizeof(s),1,fp);
printf(“%d%s%d%d%d”,s.roll_no,s.name,s.m1,s.m2,s.m3);
fclose(fp);
break;
18
scanf(“%d”,&key);
fp=fopen(“stud.dat”,”rb”);
if(fp==NULL)
exit(0);
for(i=0;i<n;i++)
fread(&s,sizeof(s),1,fp);
if(key==s.roll_no)
printf(“search successfull:”);
printf(“%d%s%d%d%d”,s.roll_no,s.name,s.m1,s.m2,s.m3);
f=1;
break;
if(f==0)
printf(“search failed:”);
}
19
break;
case 3:printf(“exit”);
exit(0);
break;
Uses:
#include<stdio.h>
void main()
{
FILE* fp;
int n[50], i = 0;
float sum = 0;
if ((fp = fopen("num.dat", "r")) != NULL)
{
puts("Reading numbers from num.dat");
while (!feof(fp))
{
fscanf(fp, "%d ", &n[i]);
printf("%d %d\n", i, n[i]);
sum += n[i];
i++;
}
fclose(fp);
if (i > 0)
20
{
float average = sum / i;
printf("The average is %f for %d numbers\n", average, i);
}
else
{
puts("No data available in num.dat!");
}
}
else
{
printf("Unable to open num.dat...\n");
}
}
fseek() - It is used to moves the reading control to different positions using fseek()
function.
ftell() - It tells the byte location of current position in file pointer.
rewind() - It moves the control to beginning of a file.
fseek() :
21
SEEK_SET The new file position will be the beginning of the file plus offset (in
bytes).
SEEK_CUR The new file position will be the current position plus offset (in bytes).
SEEK_END The new file position will be the end of the file plus offset (in bytes).
Example :
fseek(fp, 0, SEEK_SET); // go to the beginning of the file
fseek(fp, -10, SEEK_END); // back up 10 bytes from the end of the file
Returns :
The fseek function returns zero if successful. If an error occurs, the fseek function
will return a nonzero value.
Program :
22
#include <stdio.h>
void main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is ece department", fp);
fseek( fp, 7, SEEK_SET );
fputs(" cse department ", fp);
fclose(fp);
}
Let us compile and run the above program that will create a file file.txt with the following
content. Initially program creates the file and writes This is ece department but later we
had reset the write pointer at 7th position from the beginning and used puts() statement
which over-write the file with the following content “ cse department “
The final content in the file is
“ This is cse department “
ftell() :
In the C Programming Language, the ftell() function returns the current file
position indicated by the pointer in the program.
SYNTAX:
The syntax for the ftell function in the C Language is:
Variable = ftell(Filepointer);
Example : ch=ftell(fp)
The file pointer gives the current position from the beginning of the file.
RETURNS
The ftell() function returns the current file position indicator for filepointer. If
an error occurs, the ftell() function will return -1 and update error.
Program:
#include <stdio.h>
#include<stdlib.h>
23
void main ()
{
FILE *fp;
int length;
fp = fopen("file.txt", "r");
if( fp == NULL )
{
printf("cnat open");
exit(0);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
Let us assume we have a text file file.txt, which has the following content
This is cse department
Now let us compile and run the above program that will produce the following result if
file has above mentioned content otherwise it will give different result based on the file
content
Output :
Total size of file.txt = 23 bytes
Rewind() :
In the C Programming Language, the rewind() function sets the file position to
the beginning of the file for the current position of the file pointer. It also clears the error.
SYNTAX:
The syntax for the rewind function in the C Language is:
rewind(FILE pointer);
example : rewind(fp);
RETURNS:
The rewind function does not return anything.
24
Program :
#include <stdio.h>
void main()
{
char str[] = "This is cse department";
FILE *fp;
int ch; /* First let's write some content in the file */
fp = fopen( "file.txt" , "w" );
fwrite(str , sizeof(str),1 , fp );
fclose(fp);
fp = fopen( "file.txt" , "r" );
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
rewind(fp);
printf("\n");
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
fclose(fp);
}
25
Let us assume we have a text file file.txt that have the following content
This is cse department
Now let us compile and run the above program to produce the following result
Output :
This is cse department
This is cse department
feof() :
In the C Programming Language, the feof() function tests to see if the end-of-file
indicator has been set for for the file.
Syntax : feof(FILE pointer);
Example : feof(fp);
Returns :
The feof function returns a nonzero value if the end-of-file indicator is set.
Otherwise, it returns zero.
Program :
#include <stdio.h>
#include<stdlib.h>
void main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
if(fp == NULL)
{
printf("can’t open file");
exit(0);
}
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
26
break ;
}
printf("%c", c);
}
fclose(fp);
}
Until the file pointer reaches the end of the file the contents from the file will be
read and displayed in the console screen.
ferror();
In the C Programming Language, the ferror() function tests to see if there is any
error in the file input and output functions.
Syntax: ferror(FILE pointer);
Example : ferror(fp);
Returns:
The ferror() function returns a nonzero value if the error indicator is set. Otherwise,
it returns zero.
Program :
#include <stdio.h>
void main()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w");
c = fgetc(fp);
if( ferror(fp) )
{
printf("Error in reading from file : file.txt\n");
}
fclose(fp);
}
27
Assuming we have a text file file.txt, which is an empty file. Let us compile and run the
above program that will produce the following result because we try to read a file which
we opened in write only mode.
Output :
Error reading from file "file.txt"
Example Program:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
int rno;
char name;
}s;
void main()
{
FILE *fp1,*fp2;
int ch,n,f=0,i;
char a;
fp1=fopen(“stu.dat”,”w+b”);
while(1)
{
printf(“1.Add New Record\n2.Display\n3.Modify\n4.Delete\n5.Exit\n”);
printf(“Enter your Choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:printf(“Enter your roll number and name :“);
scanf(“%d%s”,&s.rno,&s.name);
fseek(fp1,0,SEEK_END);
fwrite(&s,sizeof(s),1,fp1);
break;
28
case 2:rewind(fp1);
if(fread(&s,sizeof(s),1,fp1))==0)
{
printf(“File is Empty”);
exit(0);
}
rewind(fp1);
printf(“The Records are “);
while((fread(&s,sizeof(s),1,fp1))==1)
{
printf(“%d%s”,s.rno,s.name);
}
break;
case 3:rewind(fp1);
if(fread(&s,sizeof(s),1,fp1))==0)
{
printf(“File is Empty”);
exit(0);
}
rewind(fp1);
printf(“Enter the Roll No”);
scanf(“%d”,&n);
while((fread(&s,sizeof(s),1,fp1))==1)
{
if(s.rno==n)
{
fseek(fp1,-sizeof(s),SEEK_CUR);
printf(“Enter the new roll number and name”);
scanf(“%d%s”,&s.rno,&s.name);
fwrite(&s,sizeof(s),1,fp1);
f=1;
break;
case 4:rewind(fp1);
if(fread(&s,sizeof(s),1,fp1))==0)
{
printf(“File is Empty”);
exit(0);
}
rewind(fp1);
fp2=fopen(“temp.dat”,”w+b”);
printf(“Enter roll number to delete”);
scanf(“%d”,&n);
29
while((fread(&s,sizeof(s),1,fp1))==1)
{
if(s.rno!=n)
{
fwrite(&s,sizeof(s),1,fp2);
}
if(s.rno==n)
{
f=1;
}
}
if(f)
{
printf(“Delete Successful”);
fclose(fp1);
fclose(fp2);
remove(“stu.dat”);
rename(“temp.dat”,”stu.dat”);
fp1=fopen(“stu.dat”,”r+b”);
break;
case 5:printf(“Exit”);
exit(0);
}
}
printf(“Over”);
fclose(fp1);
}
#include <stdio.h>
struct clientData
{
unsigned int acctNum;
char lastName[15];
char firstName[10];
double balance;
30
};
int main(void)
{
FILE *cfPtr;
unsigned int choice;
if ((cfPtr = fopen("credit.dat", "rb+")) == NULL)
{
puts("File could not be opened.");
}
else
{
while ((choice = enterChoice()) != 5)
{
switch (choice)
{
case 1:
textFile(cfPtr);
break;
case 2:
updateRecord(cfPtr);
break;
case 3:
newRecord(cfPtr);
break;
case 4:
deleteRecord(cfPtr);
break;
default:
puts("Incorrect choice");
break;
}
31
}
fclose(cfPtr);
}
}
if (client.acctNum == 0)
{
printf("Account #%d has no information.\n", account);
}
else
{
printf("%-6d%-16s%-11s%10.2f\n\n", client.acctNum, client.lastName,
client.firstName, client.balance);
printf("%s", "Enter charge ( + ) or payment ( - ): ");
scanf("%lf", &transaction);
client.balance += transaction; // update record balance
printf("%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName,
client.firstName, client.balance);
fseek(fPtr, (account - 1) * sizeof(struct clientData), SEEK_SET);
fwrite(&client, sizeof(struct clientData), 1, fPtr);
}
}
If any input value is passed through command prompt at the time of running of
program is known as command line argument. It is a concept to passing the arguments to
the main() function by using command prompt.
To use command line arguments in your program, you must first understand the full
declaration of the main function, which previously has accepted no arguments. In fact,
main can actually accept two arguments: one argument is number of command line
arguments, and the other argument is a full list of all of the command line arguments.
In Command line arguments application main() function will takes two arguments
that is;
}
Output
Compilation : gcc mycmd.c
Execution : ./a.out this is a program
Program name : a.out
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Explanation: In the above example.
Example
argc = 5
argv[0] = "mycmd"
argv[1] = "this"
argv[2] = "is"
argv[3] = "a"
argv[4] = "program"
argv[5] = NULL
Write a C Program to find the factorial of any number using command line argument.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int num, fact;
if(argc != 2)
{
printf("Invalid Usage.\n\n");
printf("Usage: ./a.out <number>\n");
return 0;
37
}
num = atoi(argv[1]);
if(num<0)
{
printf("Error: Factorial of negative number doesn't exist.");
return 1;
}
fact = 1;
while(num>1)
{
fact = fact * num;
num--;
}
printf("%d\n", fact);
}
EXAMPLE PROGRAMS
//FILE COPY
# include <stdio.h>
void main()
{
char c,fname[20];
FILE *fptr1,*fptr2 ;
fptr1 = fopen(“abc.txt”, "r") ;
if(fptr==NULL)
printf("\nSorry.. File Not Found");
else
{
fptr2 = fopen("dest.tx","w") ;
38
//STUDENT DETAILS
# include <stdio.h>
void main()
{
FILE *fptr ;
int i, n, rollno, s1, s2 ;
40
char name[10] ;
fptr = fopen("STUDENT.DAT", "w") ;
printf("Enter the number of students : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the roll number : ") ;
scanf("%d", &rollno) ;
printf("\nEnter the name : ") ;
scanf("%s", name) ;
printf("\nEnter the marks in 2 subjects : ") ;
scanf("%d %d", &s1, &s2) ;
fprintf(fptr, "%d %s %d %d \n", rollno, name, s1, s2) ;
}
fclose(fptr) ;
fptr = fopen("STUDENT.DAT", "r") ;
printf("\nRoll No. Name \t\t Sub1 \t Sub2 \t Total\n\n") ;
for(i = 0 ; i < n ; i++)
{
fscanf(fptr,"%d %s %d %d \n", &rollno, name, &s1, &s2) ;
printf("%d \t %s \t\t %d \t %d \t %d \n", rollno, name,s1, s2, s1 + s2) ;
}
fclose(fptr) ;
}
//No. of characters in a file
#include<stdio.h>
#include<conio.h>
Void main()
41
{
char ch;
int count=0;
FILE *fptr;
fptr=fopen("text.txt","w");
if(fptr==NULL)
{
printf("File can't be created\a");
exit(0);
}
printf("Enter some text and press enter key:\n");
while((ch=fgetc(fptr))!=EOF')
{
fputc(ch,fptr);
}
fclose(fptr);
fptr=fopen("text.txt","r");
printf("\nContents of the File is:");
while((ch=fgetc(fptr))!=EOF)
{
count++;
printf("%c",ch);
}
fclose(fptr);
printf("\nThe number of characters present in file is: %d",count);
getch();
}
//NO OF LINES IN A FILE
#include<stdio.h>
#include<stdlib.h>
void main()
42
{
FILE *fp;
char ch;
int line=0;
fp=fopen("in.txt","w");
if(fp==NULL)
{
printf("cant open");
exit(1);
}
printf("enter a character\n");
while((ch=getchar())!='$')
{
fputc(ch,fp);
}
fclose(fp);
fp=fopen("in.txt","r");
if(fp==NULL)
{
printf("cant open");
exit(1);
}
printf("content present in a file\n");
while((ch=fgetc(fp))!=EOF)
{
putchar(ch);
if(ch=='\n')
{
line++;
}
}
fclose(fp);
printf("no of lines=%d\n",line);
}
43
Important Questions
Part B Question