Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

UNIT V FILE PROCESSING

Files – Types of file processing: Sequential access, Random access – Sequential access
file -Example Program: Finding average of numbers stored in sequential access file -
Random access file -Example Program: Transaction processing using random access
files – Command line arguments.

FILES
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is
created for permanent storage of data. It is a readymade structure.

In C language, we use a structure pointer of file type to declare a file.

FILE *fp;
Why files are needed?
 When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
 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.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
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.

2. Binary files
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.

File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
Working with file
While working with file, you need to declare a pointer of type file. This declaration is
needed for communication between file and program.
FILE *ptr;
*ptr is the FILE pointer (FILE *ptr), which will hold the reference to the opened (or created)
file.

C provides a number of functions that helps to perform basic file operations. Following are
the functions,

FUNCTION DESCRIPTION

fopen() create a new file or open a existing file


fclose() closes a file getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the beginning point

fopen() and fclose() functions


Opening a File or Creating a File
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a
file in standard I/O is:
ptr=fopen("filename","mode")

Here filename is the name of the file to be opened and mode specifies the purpose of
opening
the file

MODE DESCRIPTION
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode

Closing a File
The fclose() function is used to close an already opened file. Closing a file is performed
using library function fclose().
SYNTAX:-
fclose(ptr); //ptr is the file pointer associated with file to be closed.

Input/Output operation on File

Writing to a file using fprintf( )

fprintf() works just like printf() except that its first argument is a file pointer.

Syntax:
fprintf (fptr, "Hello World!\n");
fprintf (fptr, “%d %d”, a, b);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
a=10,b=20;
fptr = fopen ("file.txt","w");
/* Check it's open */
fprintf (fptr, "Hello World!\n");
fprintf (fptr, “%d %d”, a, b);
fclose(fp);
}

OUTPUT:file.txt
Hello World!
10 20

Reading Data Using fscanf( )


It is used to read data from a file using fscanf().
Syntax:
fscanf (fptr, “%d %d”,&x, &y);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int x,y;
fptr = fopen (“input.txt”, “r”);
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in opening file \n”);
}
fscanf (fptr, “%d %d”,&x, &y);
printf(“%d%d”,x,y);
fclose(fp);
}

OUTPUT: input.txt
10 20

Reading lines from a file using fgets( )


To read a string using fgets().
fgets() takes 3 arguments – a string, maximum number of characters to read, and a file
pointer. It returns NULL if there is an error (such as EOF).
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n",line);
}
Writing lines to a file using fputs( )
The fputs() are used to write string to the file.
The fputs() function writes a line of characters into file. It outputs string to a stream.
fputs("text",fp);
text-> Any text to print
fp-> File pointer
Reading and Writing a character
A character reading/writing is equivalent to reading/writing a byte.
The function getchar() & putchar() is used to read and write a character to a file
Example:
char c;
c = getchar();
putchar(c);
Example: use of getchar() & putchar()
#include<stdio.h>
void main()
{
int c;
printf("Type text and press return to see it again \n");
printf("For exiting press \n");
while((c = getchar()) != EOF)
putchar(c);
}
OUTPUT:
Type text and press return to see it again
For exiting press

fgetc() and fputc() in C


fgetc()
fgetc() is used to obtain input from a file single character at a time. This function returns the
number of characters read by the function. It returns the character present at position
indicated by file pointer. After reading the character, the file pointer is advanced to next
character. If pointer is at end of file or if an error occurs EOF file is returned by this function.
fputs()
fputc() is used to write a single character at a time to a given file. It writes the given
character at the position denoted by the file pointer and then advances the file pointer.
This function returns the character that is written in case of successful write operation else in
case of error EOF is returned.
fgetc(FILE *pointer)

Example:
// C program to illustate fgetc() function
#include <stdio.h>

int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");

// Return if could not open file


if (fp == NULL)
return 0;

do
{
// Taking input single character at a time
char c = fgetc(fp);

// Checking for end of file


if (feof(fp))
break ;

printf("%c", c);
} while(1);
fclose(fp);
return(0);
}
Output
The entire content of file is printed character by
character till end of file. It reads newline character
as well.
fputc()
fputc() is used to write a single character at a time to a given file. It writes the given
character at the position denoted by the file pointer and then advances the file pointer.
This function returns the character that is written in case of successful write operation else in
case of error EOF is returned.
SYNTAX:-
fputc(int char, FILE *stream)
Parameters
• char -- This is character to be written. This is passed as its int promotion.
• stream -- This is the pointer to a FILE object that identifies the stream where the
character is to be written.
Return Value
If there are no errors, the same character that has been written is returned. If an error occurs,
EOF is returned and the error indicator is set.
Example
The following example shows the usage of fputc() function.
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;

fp = fopen("file.txt", "w+");
for( ch = 33 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);
return(0);
}

Example:
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Binary Files
Depending upon the way file is opened for processing, a file is classified into text file
and binary file.
If a large amount of numerical data it to be stored, text mode will be insufficient. In
such case binary file is used.
Working of binary files is similar to text files with few differences in opening modes,
reading from file and writing to file.
Opening modes of binary files
Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference
between opening modes of text and binary files is that, b is appended to indicate
that, it is binary file.

Reading and writing of a binary file.


Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of
data to be written in disk, number of such type of data and pointer to the file where
you want
to write.
Syntax:-fwrite()
fwrite(address_data,size_data,numbers_data,pointer_to_file);

Example:
#include<stdio.h>
#include<stdlib.h>
struct employee
{
char name[50];
char designation[50];
int age;
float salary
} employee;
int main()
{
int n, i, chars;
FILE *fp;
fp = fopen("employee.txt", "wb");
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fwrite() function: \n\n");
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("\nEnter details of employee %d \n", i + 1);
printf("Name: ");
gets(employee.name);
printf("Designation: ");
gets(employee.designation);
printf("Age: ");
scanf("%d", &employee.age);
printf("Salary: ");
scanf("%f", &employee.salary);
chars = fwrite(&employee, sizeof(employee), 1, fp);
printf("Number of items written to the file: %d\n", chars);
}
fclose(fp);
return 0;
}

Output:
Testing fwrite() function:
Enter the number of records you want to enter: 2

Enter details of employee 1


Name: Bob
Designation: Manager
Age: 29
Salary: 34000
Number of items written to the file: 1
Enter details of employee 2
Name: Jake
Designation: Developer
Age: 34
Salary: 56000
Number of items written to the file: 1

fread():
Function fread() also take 4 arguments similar to fwrite() function as above.
Syntax:- fread():
fread(address_data,size_data,numbers_data,pointer_to_file);
Example:
fread(&val, sizeof(int), 1, fp);

Example:
This function is used to read an entire block from a given file.
Syntax: fread ( ptr , size , nst , fptr);
Where ptr is a pointer which points to the array which receives structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.

Example:-fread():

Write a program to read an employee details at a time from a file using fread() which
are written above using fwrite()and display them on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen("emp.dat", "rb");
clrscr();
if(fp==NULL)
printf("File cannot be opened");
else
fread(&e,sizeof(e),1,fp);
printf("\nEmployee number is %d",e.eno);
printf("\nEmployee name is %s",e.ename);
printf("\nEmployee salary is %f",e.sal);
printf("One record read successfully");
getch();

}
OUTPUT:
Employee number is 10
Employee name is seshu
Employee salary is 10000.
One record read successfully

Example:
Reading and Writing from File using fprintf() and fscanf()
#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
} while( !feof(q) );
getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but
in different modes. fprintf() function directly writes into the file, while fscanf() reads from
the file, which can then be printed on console usinf standard printf() function.

Difference between Append and Write Mode


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exists already. The
only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will
not happen. Append mode is used to append or add data to the existing data of file(if any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the
present data in the file.

Sequential and Random Access File Handling in C


In computer programming, the two main types of file handling are:

 Sequential
 Random access.
Sequential files are generally used in cases where the program processes the data in a
sequential fashion – i.e. counting words in a text file – although in some cases, random
access can be feigned by moving backwards and forwards over a sequential file.

True random access file handling, however, only accesses the file at the point at which the
data should be read or written, rather than having to process it sequentially. A hybrid
approach is also possible whereby a part of the file is used for sequential access to locate
something in the random access portion of the file, in much the same way that a File
Allocation Table (FAT) works.

Example: Finding average of numbers stored in sequential access file


#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int num[10],avg,sum=0,i,n;
fp=fopen("num.txt","w");
printf("\n Enter the total numbers\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Num:");
scanf("%d",&num[i]);
fwrite(&i,sizeof(int),1,fp);
}
fclose(fp);
fp=fopen("num.txt","r");
for(i=0;i<n;i++)
{
fread(&i,sizeof(int),1,fp);
sum=num[i]+sum;
}
avg=sum/n;
printf("\n the average of numbers is is %d", avg);
fclose(fp);
getch();
}

Example For sequential access:


WRITE A PROGRAM TO COUNT THE NUMBER OF ACCOUNT HOLDERS
WHOSE BALANCE IS LESS THAN THE MINIMUM BALANCE
USING SEQUENTIAL ACCESS FILE.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust[10];
void main()
{
FILE *fp;
int i,n;
int min=5000;
clrscr();
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");
printf("enter total number of account information");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Name:");
scanf("%s",cust[i].name);
printf("Acct Num:");
scanf("%d",&cust[i].acct_num);
printf("Balance:");
scanf("%d",&cust[i].acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
}
fclose(fp);

fp=fopen("accounts.txt","r");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
else
{
printf("\n File opened for reading: accounts.txt\n\n");
}
for(i=0;i<n;i++)
{
fread(&cust,sizeof(struct customer),1,fp);
if(cust[i].acct_balance<=min)
{
printf("\n Name=%10s Acct Num =%8d Balance=%8d\n",
cust[i].name,cust[i].acct_num,cust[i].acct_balance);
}
}
getch();
fclose(fp);
}
OUTPUT:
Enter accounts information
Enter total number of account information 2
Name: Neha
Acct Num : 1
Balance: 10000
Name : Atul
Acct Num: 2
Balance: 4500

File opened for reading : accounts.txt

Name= Atul Acct Num=2 Balance=4500.00


Random Access To File

There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
1.fseek()
2.ftell()
3.rewind()

fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position.This is attached with
L because this is a long integer.

Pointer position:
This sets the pointer position in the file.

Value pointer position


0 Beginning of file.
1 Current position
2 End of file
The origin parameter can be one of three values:
 SEEK_SET – from the start;
 SEEK_CUR – from the current position;
 SEEK_END – from the end of the file.
So, the equivalent of rewind() would be:
fseek( f, 0, SEEK_SET);
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is
skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current position.
ftell()
This function returns the value of the current pointer position in the file.The value is count
from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.

Example program for fseek():


Write a program to read last ‘n’ characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{
printf("Enter value of n to read last ‘n’ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%c\t",ch);
}
}
fclose(fp);
getch();
}
OUTPUT: It depends on the content in the file.
RANDOM ASCESS EXAMPLE PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("test.txt", "r");
fseek(fp, 3, SEEK_SET);
ch=fgetc(fp);
printf("%c",ch);
fseek(fp, 3, SEEK_CUR);
ch=fgetc(fp);
printf("%c",ch);
fseek(fp, -3, SEEK_END);
ch=fgetc(fp);
printf("%c",ch);
getch();
}
TEST.TXT
PANIMALAR ENGINEERING COLLEGE
OUT PUT
IAE

Example: Transaction processing using random access files


#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust;
void main()
{
FILE *fp;
int choice=1,n;
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");

do
{
printf("\n Name:");
scanf("%s",cust.name);
printf("Acct Num:");
scanf("%d",&cust.acct_num);
printf("Balance:");
scanf("%d",&cust.acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
printf("Press 1 to enter one more entry:\n");
scanf("%d",&choice);
}while(choice==1);
fclose(fp);
fp=fopen("accounts.txt","r");
printf("\n File opened for reading: accounts.txt\n\n");
printf("\n Enter which customer detail has to be printed");
scanf("%d",&n);
fseek(fp,n*sizeof(struct customer),0);
fread(&cust,sizeof(struct customer),1,fp);
printf("\n Name=%10s Acct Num =%8d Balance=%d\n",
cust.name,cust.acct_num,cust.acct_balance);
getch();
}

Basic C- Files Examples:-


1.Write a C program to read name and marks of n number of students from
user and store them in a file.
#include <stdio.h>
#include<conio.h>
int main()
{
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;
}
2.Write a C program to read name and marks of n number of students from
user and store them in a file. If the file previously exits, add the information
of n students.
#include <stdio.h>
#include<conio.h>
int main()
{
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;
}
3.Write a C program to write all the members of an array of structures to a file
using fwrite(). Read the array from the file and display on the screen.
#include<stdio.h>
#include<conio.h>
struct s
{
char name[50];
int height;
};
int main()
{
struct s a[5],b[5];
FILE *fptr;
int i;
clrscr();
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
getch();
}

Command line arguments


main() function of a C program accepts arguments from command line or from other shell
scripts by following commands. They are,
1. argc
2. argv[]
where,
argc – Number of arguments in the command line including program name
argv[] – This is carrying all the arguments
Remember that argv[0] holds the name of the program and argv[1] points to the first
command line argument and argv[n] gives the last argument. If no argument is supplied, argc
will be 1.
In real time application, it will happen to pass arguments to the main program itself. These
arguments are passed to the main () function while executing binary file from command line.
For example, when we compile a program (test.c), we get executable file in the name “test”.
Now, we run the executable “test” along with 4 arguments in command line like below.
where
argc = 5
argv[0] = “test”
argv[1] = “this”
argv[2] = “is”
argv[3] = “a”
argv[4] = “program”
argv[5] = NULL
Procedure:To execute command line arguments
1. Save your file with name test.c
2. Compile and Execute the program
3. Open a dos shell.In that Type a command
C:\TURBOC3>BIN\cd..
C:\TURBOC3>cd SOURCE
C:\TURBOc3\SOURCE>test.exe this is a program

Example:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) // command line arguments


{
if(argc!=5)
{
printf("Arguments passed through command line " \
"not equal to 5");
return 1;
}

printf("\n Program name : %s \n", argv[0]);


printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);

return 0;
}
OUTPUT:
Program name : test.c
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)

Example:
#include <stdio.h>
int main( int argc, char *argv[] )
{

if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
OUTPUT:
One argument expected
C:\TURBOC3>BIN\cd..
C:\TURBOC3>cd SOURCE
C:\TURBOc3\SOURCE>cmd.exe testing
The argument supplied is testing
C:\TURBOc3\SOURCE>cmd.exe testing testing1
Too many arguments supplied

You might also like