Unit 5
Unit 5
Unit 5
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.
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
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.
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
OUTPUT: input.txt
10 20
Example:
// C program to illustate fgetc() function
#include <stdio.h>
int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");
do
{
// Taking input single character at a time
char c = fgetc(fp);
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.
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
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.
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.
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
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.
#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
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();
}
Example:
#include <stdio.h>
#include <stdlib.h>
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