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

File handling in c pdf 2

The document provides an overview of file handling in C, detailing high-level I/O functions for reading and writing data to files. It explains file operations such as opening, closing, and error handling, as well as random access file processing and command line arguments. Key functions like fopen(), fclose(), fprintf(), and fscanf() are highlighted for their roles in file manipulation.

Uploaded by

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

File handling in c pdf 2

The document provides an overview of file handling in C, detailing high-level I/O functions for reading and writing data to files. It explains file operations such as opening, closing, and error handling, as well as random access file processing and command line arguments. Key functions like fopen(), fclose(), fprintf(), and fscanf() are highlighted for their roles in file manipulation.

Uploaded by

conquerxclash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

12.

1 INTRODUCTION
• File Handling is the storing of data in a High-level I/O functions
file using a program. Function Description
• the programs store results, and other data
of the program to a file using file fopen() function is used to create a new file or open
handling in C. an existing file in C.
• Also, we can extract/fetch data from a file fclose() Closes as a file
to work with it in the program.
fprintf ( ) write data into a file
File operations
fscanf ( ) read data from a file
1. Naming a file
2. Opening an existing file putc ( )/ write a character into a file
fputc()
3. Reading data from an existing file
getc ( ) read a character from a file
4. Writing data to a file
/fgetc()
5. Closing the file
putw ( ) write a number into a file
Two ways to perform the operations in c.
1. low-level i/o and uses UNIX getw ( ) read number from a file

2. High-level i/o and uses functions in C’s fputs ( ) write a string into a file
standard library. fgets ( ) read a string from a file
fread() read an entire record from a file
fwrite() write an entire record into a file
12.2 DEFINING AND OPENING A FILE
• To store data in a file in the secondary 1. fp as a file pointer to the data type FILE.
memory, we must specify 2. Filename- the file opened in the named
1. Filename filename and assign an identifier to the
FILE type pointer fp.
2. Data structure
3. Mode- It is a string (usually a single
3. Purpose
character ) that specifies the mode in
• file_name − It is a string that specifies the which the file is to be opened.
name of the file that is to be opened or
“r” − open for reading
created using the fopen method.
“rb” − open for reading in binary mode
It may contain two parts
“w” − open for writing only
A primary name and an optional period
with the extension. “wb” − open for writing in binary mode
• Data structure of a file is defined as FILE “a” − open for append only
in the library of standard I/O functions “ab” − open for append in binary
definition. “r+” − open for reading and writing both
• Purpose-what we want to do with the file. “rb+” − open for reading in binary mode
Example “w+” − open for writing and reading
FILE *fp; “wb+” - open for writing and reading in
fp = fopen(“file_name”, “mode”); binary mode
“a+” − open for read and append
“ab+” − open for read and append in binary
12.3 CLOSING A FILE
• A file must be closed as soon as the all • Once the file is closed, its file pointer can
operations are completed. be reused for another file.
fclose(file_pointer); • All files are closed automatically
• Close file associated with the FILE pointer whenever a program terminates.
file_pointer.
Example
----------
----------
FILE *fp1,*fp2;
fp1=fopen(“INPUT”,”w”);
fp2=fopen(“OUTPUT”,”r”);
----------
----------
fclose(fp1);
fclose(fp2);
12.4 INPUT/OUTPUT OPERATIONS ON FILES
The getc() and putc() function #include <stdio.h>
• The file is opened with mode w and int main()
filepointer fp1. {
putc(c,fp1); FILE *fp;
• Writes a character contained in the char c;
character variable c to the file associated printf("Data Input\n");
with FILE pointer fp1.
fp=fopen("INPUT.TXT","w");
c=getc(fp2);
while ((c=getchar()) != EOF)
• Reads a character from the file whose file
pointer is fp2. putc(c,fp);
• The file pointer moves by one character fclose(fp);
position for every operations of getc() and printf("Data Output\n");
putc(). fp=fopen("INPUT.TXT","r");
Example while ((c=getc(fp))!=EOF)
printf("%c",c);
fclose(fp);
return 0;
}
get() and putw() functions printf("Data Output\n");
• Integer oriented functions. f1=fopen("DATA.TXT","r");
• Used to read and write integer values. while ((n=getw(f1))!=EOF)
putw(integer,fp); printf("%d",n);
integer_variable=getw(fp); fclose(f1);
Example return 0;
#include <stdio.h> }
int main() Output
{ Data file
FILE *f1; 1
int n,i; 2
printf("Data file\n"); 3
f1=fopen("DATA.TXT","w"); 4
for (i=1;i<=10;i++) 5
{ 6
scanf("%d",&n); -1
if(n== -1) break; Data Output
putw(n,f1); 1 2 3 4 5 6
} .
fclose(f1);
fscanf() and fprintf() functions
printf("Item Name no price Quantity\n");
• These functions are used performed I?O for(i=1;i<=3;i++)
operations on files.
{
fprintf(fp,”control string”,list); scanf("%s %d %f %d", item, &n, &price, &qty);
fscanf(fp,control string”,list); fprintf(fp,"%s %d %f %d",item,n,price,qty);
• Where fp is a file pointer associate with a }
file that has been opened for writing. fclose(fp);
• The control string contains output printf("Data Output\n");
specifications for the items in the list. fp=fopen(filename,"r");
• The list may include variables, constants printf("Item Name no price Quantity\n");
and strings. for(i=1;i<=3;i++)
Example {
fscanf(fp,"%s %d %f %d",item,&n,&price,&qty);
#include <stdio.h>
printf("%s %d %f %d\n",item,n,price,qty);
int main()
}
{ fclose(fp);
FILE *fp; int n,qty,i; return 0;
float price,value; }
char item[10],filename[10]; Output
printf("Input file name\n");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("input inventory details\n");
Output

Input file name


pen
input inventory details
Item Name no price Quantity

note
1
50.50
100
pencil
2
56.90
290
paper
3
120.00
500
Data Output
Item Name no price Quantity

note 1 50.500000 100


pencil 2 56.900002 290
paper 3 120.000000 500
12.5 ERROR HANDLING DURING I/O
OPERATIONS
Error situations
1. Trying to read beyond the end-of-file mark.
2. Device overflow
3. Trying to use a file that has not been opened.
4. Trying to perform an operations on a file, when the file is opened for another type of
operations
5. Opening a file with an invalid filename
6. Attempting to write to a write-protected file.
• foef-use to test for an end of file condition.
• ferror-reports status of the file indicated.
Example for(i=10;i<=100;i+=10)
#include <stdio.h> {
int main() n=getw(fp2);
{ if (feof(fp2))
char *filename; {
FILE *fp1,*fp2; printf("Run out of data\n");
int i,n; break;
fp1=fopen("TEST.TXT","w"); }
for (i=10;i<=100;i+=10) else .
putw(i,fp1); printf("%d\n",n);
fclose(fp1); }
printf("Input filename"); fclose(fp2);
s:scanf("%s",filename); return 0;
if ((fp2=fopen(filename,"r"))== NULL) }
{
printf("Cannot open the file\n");
printf("Try again\n");
goto s;
}
Else
Output
Input filenametet
Cannot open the file
Try again
TEST.TXT

10
20
30
40
50
60
70
80
90
100
12.6 RANDOM ACCESS FILE
• functions for random access file
processing. value meaning
1. fseek() 0 Beginning of the file
2. ftell() 1 Current position
3. rewind()
2 End of the file
fseek()
This function is used for seeking the .
pointer position in the file at the specified
Statement Meaning
byte.
Syntax fseek(fp,0l,0); Got o the beginning
fseek( file_ptr, offset, position); fseek(fp,0l,1); Stay at the current position
file_ptr :pointer to the file concerned.
fseek(fp,0l,2); Go to the end of the file
offset: is a number or variale of type long.
fseek(fp,m,0); Move to (m+1)th byte in the
the no. positions (bytes) to be moved
file
from the location specified by position.
fseek(fp,m,1); Go forward by m bytes
position: is an integer number.
The position can take one of the three values. fseek(fp,-m10); Go backward by m bytes
from the current position
The offset may be positive, meaning move
fseek(fp,-m,2); Go backward by m bytes
forwards, or negative, meaning move
from the end
backwards
Example printf("\nThe current position of the file
#include <stdio.h> pointer is: %ld\n", ftell(fp));
int main () rewind(fp);
{ printf("The current position of the file pointer
FILE *fp; is: %ld\n", ftell(fp));
int c; printf("After rewrite the contents\n");
fp = fopen("OUTPUT.txt","w+"); printf("Read the Random Access File\n");
fputs("Random Access file example", fp); while(1)
fseek( fp, 0, SEEK_SET ); {
printf("Random Access file contains\n"); c = fgetc(fp);
while(1) if( feof(fp))
{ {
c = fgetc(fp); break;
if( feof(fp)) }
{ printf("%c", c);
break; }
} fclose(fp);
printf("%c", c); return(0);
} }
fputs("\nC Programming E Balagurusamy", fp);
fputs("\nsecond edition", fp);
Output
Random Access file contains
Random Access file example
The current position of the file pointer is: 70
The current position of the file pointer is: 0
After rewrite the contents
Read the Random Access File
Random Access file example
C Programming E Balagurusamy
second edition
12.7 COMMAND LINE ARGUMENTS
What is a command line argument? #include <stdio.h>
void main( int argc, char *argv[] )
• It is a parameter supplied to a program when the
{
program is invoked. FILE *fp;
• This parameter may represent a filename the int i;
program should process. Char word[15];
• The command line arguments are handled using fp=fopen(argv[1],"w");
main() function arguments where argc refers to printf("No. of arguments in command line =%d\n",argc);
for(i=2;i<argc;i++)
the number of arguments passed, and argv[] is a
{
pointer array which points to each argument
fprintf(fp,"%s",argv[1]);
passed to the program. }
• In order to access the command line arguments, fclose(fp);
we must declare the main() function and its printf("contents of %s file \n",argv[1]);
parameters are fp=fopen(argv[1],"r");
main(int argc,char *argv[]) for(i=2;i<argc;i++)
{
{ fscanf(fp,"%s",word);
------------- printf("%s",word);
------------- }
fclose(fp);
}
printf("\n\n");
for(i=0;i<argc;i++)
printf("%s\n",argv[i]);
}

You might also like