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

Unit V File Processing: Text Files

The document discusses various file processing concepts including: - Sequential and random access files with example programs for each. - File input/output functions like fopen(), fclose(), getw(), putw(), fgetc(), fputc(), fgets(), fputs(), fwrite(), and fread(). - Example programs demonstrating the use of these functions to read and write data from/to files.

Uploaded by

Parthiban M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
183 views

Unit V File Processing: Text Files

The document discusses various file processing concepts including: - Sequential and random access files with example programs for each. - File input/output functions like fopen(), fclose(), getw(), putw(), fgetc(), fputc(), fgets(), fputs(), fwrite(), and fread(). - Example programs demonstrating the use of these functions to read and write data from/to files.

Uploaded by

Parthiban M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

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

File
A file is a named collection of related information that is recorded on
secondary storage such as magnetic disks, magnetic tapes and optical disks.
In general, a file is a sequence of bits, bytes, lines or records whose meaning
is defined by the files creator and user.
Types of Files
There are 2 kinds of files in which data can be stored in 2 ways either in
characters coded in their ASCII character set or in binary format. They are
Text Files- Ex: Notepad,Word..
Binary Files- Ex pdf, jpeg,mp3..
Text Files
A Text file contains only the text information like alphabets ,digits and
special symbols. The ASCII code of these characters are stored in these files.
Binary Files
A binary file is a file that uses all 8 bits of a byte for storing the
information .It is the form which can be interpreted and understood by the
computer.
The only difference between the text file and binary file is the data contain
in text file can be recognized by the word processor while binary file data
can’t be recognized by a word processor.
Modes of Operation
File Access Mechanisms

File access mechanism refers to the manner in which the records of a file
may be accessed.There are several ways to access files:
Linear/Sequential access
Direct/Random access
Indexed sequential access
Sequential access
A sequential access is that in which the records are accessed in some
sequence, i.e., the information in the file is processed in order, one record
after the other. This access method is the most primitive one. Example:
Compilers usually access files in this fashion.
Direct/Random access
Random access file organization provides, accessing the records directly.
Each record has its own address on the file with by the help of which it can
be directly accessed for reading or writing.
The records need not be in any sequence within the file and they need not be
in adjacent locations on the storage medium.
Indexed sequential access
This mechanism is built up on base of sequential access.
An index is created for each file which contains pointers to various blocks.
Index is searched sequentially and its pointer is used to access the file
directly.

Streams
A Stream refers to the characters read or written to a program. The streams
are designed to allow the user to access the files efficiently .A stream is a
file or physical device like keyboard, printer and monitor.
The FILE object contains all information about stream like current position,
pointer to any buffer, error and EOF(end of file).
C supports a number of functions that have the ability to perform the basic
file operations which includes :
naming a file
opening a file
reading data from a file
writing data into a file
closing a file

I/O Operations
Once a file is opened, reading out of or writing to it is accomplished using
the standard I/O routines.
fopen() : It creates a new file for use or opens an existing file for use.
fclose() : It closes a file which has been opened for use.
getw() : This function returns the integer value from a given file and
increment the file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
putw() : This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a
given file.

Example Program for getw() and putw()


Write a program to read integer data from the user and write it into the file
using putw() and read the same integer data from the file using getw() and
display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen("c.dat", "wb+");
printf("Enter the integer data");
scanf("%d",&n);
while(n!=0)
{
putw(n,fp);
scanf("%d",&n);
}
rewind(fp);
printf("Reading data from file");
while((n=getw(fp))!=EOF)
{
printf("%d\n",n);
}
fclose(fp);
getch();
}

OUTPUT:
Enter the integer data
10
20
34
45
0
Reading data from file
10
20
34
45
0

fgetc ()
This function is same as the getc () function. It also reads a single character
from a given file and increment the filepointer.It returns EOF,if the end of
the file is reached or it encounters an error.
Syntax: fgetc (fptr);
ch=fgetc (fptr);
Where fptr is a file pointer.
ch is a variable which receive the character returned by fgetc ().
fputc()
This function writes the character to the specified stream at the current file
position and then increments the file position indicator.
Syntax: fputc(ch,fptr);
Where fptr is a file pointer
ch is a variable written to the file which is pointed by file pointer.

Example program for fgetc() and fputc():


Write a program to read character by character from the user and write them
into a file using fputc() and read the same data from the file using fgetc() and
display that on the screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("a.txt", "w+");
printf("Enter data into file\n");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
printf("Reading data from file\n");
rewind(fp); // Here rewind() will move file pointer to the beginning of
the file
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
}

OUTPUT:
Enter data into file
Hai hello how r u I am fine
Reading data from a file
Hai hello how r u I am fine

fgets()
This function is used to read a string from a given file and copies the string
to a memory location which is referenced by an array.
Syntax: fgets(sptr,max,fptr);
Where sptr is a string pointer, which points to an array.
max is the length of the array.
fptr is a file pointer ,which points to a given file.
This function read max-1 characters and places them into array which is
pointed by sptr.This function read character until either a newline or an end
of the file or size of the array occurs. It appends a null character (‘\0’) at the
end of the string. It returns a null pointer if either an end of file or an error
encountered.

fputs()
This function is used to write a string to a given file.
Syntax: fputs (sptr, fptr);
Where sptr is a pointer which points to an array
fptr is a file pointer which is pointed to a given file.

Example program for fgets() and fputs()


Write a program to read multiple number of strings from the user and write
them to a file using fputs() and read the same strings from file using fgets()
and display on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char st[80];
clrscr();
fp=fopen("a.txt", "w+");
printf("Enter data into file (type end to stop)\n");
gets(st);
while(strcmp(st, "end")!=0)
{
fputs(st,fp);
fputs("\n",fp);
gets(st);
}
rewind(fp);
printf("Reading data from file");
fgets(st,80,fp);
while(feof(fp)==0) //feof() will check whether end of file has been
reached or not.
{
puts(st);
fgets(st,80,fp);
}
fclose(fp);
getch();
}

OUTPUT:
Enter data into file (type end to stop):
Hello
Hai
How r u
end
Reading data from file
Hello
Hai
How r u
end

Block read/write
It is useful to store the block of data into the file rather than individual
elements.Each block has some fixed size,it may be of strcture or of an
array.It is possible that a data file has one or more structures or arrays,So it
is easy to read the entire block from file or write the entire block to the
file.There are two useful functions for this purpose

1. fwrite():
This function is used for writing an entire block to a given file.
Syntax: fwrite( ptr, size, nst, fptr);
Where ptr is a pointer which points to the arrayof struture in which data is
written.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
Example program for fwrite():
Write a program to read an employee details and write them into the file at a
time using fwrite().
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen("emp.dat", "wb");
clrscr();
printf("Enter employee number");
scanf("&d",&e.eno);
printf("Enter employee name");
fflush(stdin);
scanf("%s",e.ename);
printf("Enter employee salary");
scanf("%f",&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf("One record stored successfully");
getch();
}

OUTPUT:
Enter employee num: 10
Enter employee name : seshu
Enter employee salary : 10000
One record stored successfully.

2. fread()
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 program for 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.
3. fprintf()
This function is same as the printf() function but it writes the data into the
file, so it has one more parameter that is the file pointer.
Syntax: fprintf(fptr, "controlcharacter",variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be printed into file.
Variable-names hold the data to be printed into the file.

4. fscanf()
This function is same as the scanf() function but this reads the data from the
file, so this has one more parameter that is the file pointer.
Syntax: fscanf(fptr, "control character", &variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be read from the file.
Address of Variable names are those that hold the data read from the file.

Example for fprintf() and fscanf()


Write a program to read details of an employee and print them in a file using
fprintf() and read the same from the file using fscanf() and display on the
output screen.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int eno;
char ename[20];
float sal;
clrscr();
fp=fopen("emp.dat", "w+");
printf("Enter employee number");
scanf("&d",eno);
printf("Enter employee name");
fflush(stdin);
scanf("%s",ename);
printf("Enter employee salary");
scanf("%f",sal);
fprintf(fp, "%d %s %f\n",eno,ename,sal);
printf("Details of an employee are printed into file");
rewind(fp);
fscanf(fp,"%d %s %f",&eno,ename,&esal);
printf("Details of employee are\n");
printf("\n %d %s %f", eno,ename, sal);
fclose(fp);
getch();
}
OUTPUT:
Enter employee num: 10
Enter employee name : seshu
Enter employee salary : 10000
Details of an employee are printed into file.
Details of employee are
Employee number is 10
Employee name is seshu
Employee salary is 10000.

feof()
The macro feof() is used for detecting whether the file pointer is at the end
of file or not.It returns nonzero if the file pointer is at the end of the file
otherwise it returns zero.
Syntax: feof(fptr);
Where fptr is a file pointer .

ferror()
The macro ferror() is used for detecting whether an error occur in the file on
filepointer or not.It returns the value nonzero if an error,otherwise it returns
zero.
Syntax: ferror(fptr);
Where fptr is a file pointer.
Sequential and Random file access
1.Sequential Access: In this type of files data is kept in sequential order if
we want to read the last record of the file,we need to read all records before
that record so it takes more time.
2.Random Access : In this type of files data can be read and modified
randomly .If we want to read the last record we can read it directly.It takes
less time when compared to sequential file.
Example: Find Average of N numbers in File using Sequential Access

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
FILE *inFile;
char fname[30];
int sum,avg,num;
int n;
sum=0.0;
n=0;
printf("\nEnter a file name: ");
gets(fname);
inFile = fopen(fname, "r");
if (inFile == NULL)
{
printf("\nFailed to open file.\n");
exit(1);
}

while(!feof(inFile))
{
fscanf(inFile,"%d",&num);
printf("num=%d\n",num);
sum=sum+num;
n=n+1;
}
printf("\nSum=%d\n",sum);
avg=sum/n;
fclose(inFile);
printf("\nAverage=%d",avg);
getch();
return 0;

Output:

Change input numbers of sum.txt


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.
fseek()
ftell()
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

Ex:
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.

Example : Program to add customer information in file using Random


access

// Writing data randomly to a random-access file

#include <stdio.h>

// clientData structure definition


struct clientData
{
unsigned int acctNum; // account number
char lastName[ 15 ]; // account last name
char firstName[ 10 ]; // account first name
int balance; // account balance
}; // end structure clientData

int main( void )


{
FILE *cfPtr; // credit.txt file pointer
// create clientData with default information
struct clientData client = { 0, "", "", 0 };

// fopen opens the file; exits if file cannot be opened


if ( ( cfPtr = fopen( "credit.txt", "rb+" ) ) == NULL )
{
puts( "File could not be opened." );
} //end if

else
{

// require user to specify account number


printf( "%s", "Enter account number"
" ( 1 to 100, 0 to end input )\n? " );
scanf( "%d", &client.acctNum );

// user enters information, which is copied into file


while ( client.acctNum != 0 )
{

// user enters last name, first name and balance


printf( "%s", "Enter lastname, firstname, balance\n? " );

// set record lastName, firstName and balance value


fscanf( stdin, "%14s%9s%d", client.lastName,
client.firstName, &client.balance );

// seek position in file to user-specified record


fseek( cfPtr, ( client.acctNum - 1 ) *
sizeof( struct clientData ), SEEK_SET );

// write user-specified information in file


fwrite( &client, sizeof( struct clientData ), 1, cfPtr );

// enable user to input another account number


printf( "%s", "Enter account number\n? " );
scanf( "%d", &client.acctNum );
} // end while

fclose( cfPtr ); // fclose closes the file

} // end else
getch();
return 0;

} // end main

Output:
/*
credit.txt file will be opened and data entered in output screen will get stored
in file.
*/

Command Line Arguments


It is possible to pass some values from the command line to your C
programs when they are executed. These values are called command line
arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard coding
those values inside the code.
Command-line arguments are given after the name of the program in
command-line shell of Operating Systems. To pass command line
arguments, we typically define main() with two arguments :
first argument is the number of command line arguments and
second argument is list of command-line arguments.
Syntax:
int main(int argc, char *argv[]) { /* ... */ }
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer
array which points to each argument passed to the program.
// C program for finding the largest integer
// among three numbers using command line arguments

#include<stdio.h>

// Taking argument as command line


int main(int argc, char *argv[])
{
int a, b, c;

// Checking if number of argument is equal to 4 or not.


if (argc < 4 || argc > 5)
{
printf("enter 4 arguments only eg.\"filename arg1 arg2 arg3!!\"");
return 0;
}

// Converting string type to integer type using function


"atoi( argument)"
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);

// Checking if all the numbers are positive of not


if (a < 0 || b < 0 || c < 0)
{
printf("enter only positive values in arguments !!");
return 1;
}

// Checking if all the numbers are different or not


if (!(a != b && b != c && a != c))
{
printf("please enter three different value ");
return 1;
}
else
{
// Checking condition for "a" to be largest
if (a > b && a > c)
printf("%d is largest", a);
// Checking condition for "b" to be largest
else if (b > c && b > a)
printf ("%d is largest", b);

// Checking condition for "c" to be largest..


else if (c > a && c > b)
printf("%d is largest ",c);
}
return 0;
}

Output:

You might also like