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

File Processing

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

KEC – Programming in C – UNIT 5 – File Processing

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.
5.1 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. 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, the y 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

1
KEC – Programming in C – UNIT 5 – File Processing

security than text files.


File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
5. 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

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
Syntax:
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created)
*fp = FILE *fopen(const char *filename, const char *mode);
file.
filename is the name of the file to be opened and mode specifies the purpose of openin g the file.

2
KEC – Programming in C – UNIT 5 – File

Mode can be of following types,

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 alread y opened
file. Syntax :

int fclose( FILE *fp);


Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
Input/ Output operation on File
In the above table we have discussed about various file I/O functions to perform reading and
writing on file. getc() and putc() are the simplest functions which can be used to read and write
individual characters to a file.
Example:
#include<stdio.h>
int main()

{
3
KEC – Programming in C – UNIT 5 – File

FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF)
{ putc(ch, fp); }
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
// closing the file pointer
fclose(fp);
return 0;
}
Reading and Writing to File using fprintf() and fscanf()
#include<stdio.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

4
KEC – Programming in C – UNIT 5 – File

{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two F ILE 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 the console using 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 alread y 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.

Reading and Writing in a Binary File


A Binary file is similar to a text file, but it contains only large numerical data. The Opening
modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.

Syntax for writing a binary file:


fread() is also used in the same way, with the same arguments like fwrite() function. Below
fwrite(data-element-to-be-written, size_of_elements, number_of_elements, pointer-to-file);
mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");

5
KEC – Programming in C – UNIT 5 – File

if (bfp)

6
KEC – Programming in C – UNIT 5 – File

fwrite(mytext, sizeof(char), strlen(mytext), bfp);


fclose(bfp);
}
5.2 TYPES OF FILE PROCESSING: SEQUENTIAL ACCESS, RANDOM ACCESS
In computer programming, the two main types of file handling are:
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.

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.

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():
It is used to move the reading control to different positions using fseek function.
Syntax:

7
KEC – Programming in C – UNIT 5 – File

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.

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(): It tells the byte location of current position of cursor in file pointer.
rewind(): It moves the control to beginning of the file.
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>

8
KEC – Programming in C – UNIT 5 – File

#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();
}
5.3 COMMAND LINE ARGUMENTS
Command line argument is a parameter supplied to the program when it is invoked. Command
line argument is an important concept in C programming. It is mostly used when you need to
control your program from outside. Command line arguments are passed to
the main() method.
Syntax:

int main(int argc, char


Here argc counts the number of arguments on the command line and argv[ ] is a pointer array
*argv[])
which holds pointers of type char which points to the arguments passed to the program.

9
KEC – Programming in C – UNIT 5 – File

Example:
#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
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.

You might also like