0% found this document useful (0 votes)
11 views12 pages

FILE Handling notes

The document provides an overview of file handling in C, detailing how to open, read, write, and close files using various functions. It explains the structure of a file, the use of FILE pointers, and the different modes for file access. Additionally, it covers important functions like fopen, fclose, fprintf, fscanf, and methods for handling formatted I/O and random access to files.

Uploaded by

abhishek rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views12 pages

FILE Handling notes

The document provides an overview of file handling in C, detailing how to open, read, write, and close files using various functions. It explains the structure of a file, the use of FILE pointers, and the different modes for file access. Additionally, it covers important functions like fopen, fclose, fprintf, fscanf, and methods for handling formatted I/O and random access to files.

Uploaded by

abhishek rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

FILE:

A file is a collection of bytes stored on a secondary storage device. The collection of bytes may
be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical image.
When accessing files through C, the first necessity is to have a way to access the files. For C
File I/O you need to use a FILE pointer, which will let the program keep track of the file being
accessed. For Example:
FILE *fp;
Text files: A text file can be a stream of characters that a computer can process sequentially.

FILE Functions
Reading from or writing to a file in C requires 3 basic steps:

1. Open the file.


2. Do all the reading or writing.
3. Close the file.

Defining and Opening a file:

If we want to store data in a file in the secondary memory, we must specify certain things about the
file, to the operating system. They include:

1. Filename
2. Data structure
3. Purpose

Filename is a string of characters that make up a valid filename for the operating system. It
may contain two parts, a primary name and an optional period with the extension. Examples:

Input.data
Store
Prog.c
Student.c
Text.out

Data structure of a file is defined as FILE in the library of standard I/O function definitions.
So all files should be declared as type FILE before they are used.

Following is general format for declaring and opening a file:

FILE *fp;

fp=open(“filename”,”mode”);

The first statement declares the variable fp as a “pointer to the data type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This
pointer which contains all the information about the file is subsequently used as a communication link
between the system and the program.

 filename is a string that holds the name of the file on disk


 mode is a string representing how you want to open the file.

Modes are
w - open for writing (file need not exist)
r - open the file for reading only.
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Here's a simple example of using fopen:
FILE *fp;
fp=fopen("test.txt", "r");
This code will open test.txt for reading in text mode. To open a file in a binary mode you must
add a b to the end of the mode string; for example, "rb" (for the reading and writing modes, you can
add the b either after the plus sign - "r+b" - or before - "rb+")

Important file handling functions that are available in the C library.

Function name Operation


fopen() Creates new file for use & Opens an existing file for use.
fclose() Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current passion in the file(in terms of bytes from the start)
rewind() Sets the position to the beginning of the file.
fgetc()
fputc()
getchar()
getch()

Reading from or writing to a file using Formatted I/O,

Once a file has been successfully opened, you can read from it using fscanf() or write to it
using fprintf(). These functions work just like scanf() and printf(), except they require an extra first
parameter, a FILE * for the file to be read/written.

fprintf(fp, "This is testing...\n");

The function fscanf(), like scanf(), normally returns the number of values it was able to read in.
fscanf(fp,"%s",&sent);

To test for end of file is with the library function feof(). It just takes a file pointer and returns a
true/false value based on whether we are at the end of the file.

To read the data from the file until end of file

while (!feof(fp))
{
fscanf(fp, "%s”, username)
printf(“\n %s”,username);
}

Note that, like testing != EOF, it might cause an infinite loop if the format of the input file was not as
expected.

Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures that all
outstanding information associated with the file is flushed out from from the buffers and all links to
the file are broken.

fclose(file_pointer);

Example: (file1.c)
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen(“test.txt", "w"); /* file(text.txt) opening in write mode*/
fprintf(fp, "This is testing...\n");

fclose(fp);
}

This will create a file test.txt in and will write This is testing in that file.
Output at file(test.txt):
Hello, This is testing...

Example:
//Program to create a data file containing student records*/
#include<stdio.h>
main()
{
FILE *fp;
int stno;
char stname[10];
int m1,m2,m3,n,i;
fp=fopen("stu.dat","w");
printf("enter no of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nstno: ");
scanf("%d",&stno);
printf("stname: ");
scanf("%s",stname);
printf("m1 m2 m3: ");
scanf("%d%d%d",&m1,&m2,&m3);
fprintf(fp,"%d %s %d %d %d\n",stno,stname,m1,m2,m3);
}
fclose(fp);

}
Output: 101 xyz 90 80 95
enter no of students: 2 stno: 102
stno: 101 stname: pqr
stname: xyz m1 m2 m3: 88 87 89
m1 m2 m3: 90 80 95 102 pqr 88 87 89

Input / Output operations on Files

The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).

Thus the statement

c = getc(fp);

reads the next character from the file referenced by fp and the statement

putc(c,fp);

writes the character c into file referenced by fp.

/* file1.c: Display contents of a file on screen */

Example program:
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c ;
fp = fopen( "file1.c", "r" );
c = getc( fp ) ;
while ( c != EOF )
{
putchar( c );
c = getc ( fp );
}
fclose( fp );
}
Output: (from file1.c)
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp,"Hello, This is testing...\n");
fclose(fp);
}
Another Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
char c;
clrscr();
printf("input:\n");
f1 = fopen("file3","w"); /* open file input*/
while((c=getchar())!=EOF) /* get character from keyboard*/
putc(c,f1); /* write a character to file3*/
fclose(f1); /* close the file*/
f1=fopen("file3","r"); /* re open the file*/
printf("output:\n");
while((c=getc(f1))!=EOF) /* display character on screen*/
printf("%c",c);
fclose(f1);
getch();
}
Output:
input:
hai hello, this is nec....Ece.b students designed me..^Z
output:
hai hello, this is nec....Ece.b students designed me..

The getw and putw functions

The getw and putw are integer-oriented functions. They are similar to the getc and putc
functions and are used to read and write integer values. These functions would be useful when we deal
with only integer data. The general form of getw and putw are:

putw(integer, fp);
getw(fp);

Example program:
/*usage of getw, putw functions....*/
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Contents of DATA file:\n\n");
f1=fopen("DATA","w");
for(i=1;i<=30;i++)
{
scanf("%d",&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);

f1=fopen("DATA","r");
f2=fopen("EVEN","w");
f3=fopen("ODD","w");
while((number=getw(f1))!=EOF)
{
if(number%2==0)
{
putw(number,f2);
}
else
putw(number,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);

f2=fopen("EVEN","r");
f3=fopen("ODD","r");

printf("\n contents of ODD file\n");


while((number=getw(f3))!=EOF)
printf("%4d",number);
printf("\n contents of EVEN file\n");
while((number=getw(f2))!=EOF)
printf("%4d",number);
fclose(f2);
fclose(f3);
getch();
}
Output:
Contents of DATA file:
1 2 3 4 5 6 7 8 9 10 11 -1

contents of ODD file


1 3 5 7 9 11
contents of EVEN file
2 4 6 8 10
7|Page

The fprintf and fscanf Functions

The functions fprintf and fscanf perform I/O operations that are identical to the
familiar printf and fscanf functions, except of course that they work on files. The first
argument of these functions is a file pointer which specifies the file to be used. The general
form of fprintf is

fprintf(fp, “control strings”,list);

where fp is file pointer associated with a file that has been opened for writing.
The control strings contains output specifications for the items in the list. (%d,%f,%s,%u,%e,
etc)
The list may include variables, constants and strings.

example is fprintf(f1,”%s %d %f”, name, age, percentage);


here f1 is file pointer.
The general form of fprintf is

fscanf(fp, “control strings”,list);

example is fprintf(f1,”%s %d %f”, name, &age, &percentage);

Example program:
/*usage of fprintf,fscanf functions....*/
#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[10],filename[10];
printf("input file name:\n");
scanf("%s",filename);
fp=fopen(filename,"w"); // “18jan.txt”
printf("Input inventary data\n");
printf("itemname number price quantity \n");
for(i=1;i<=3;i++)
{
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %f %d",item,number,price,quantity);
}
fclose(fp);
fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("itemname number price quantity value\n");
for(i=1;i<=3;i++)
{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;
8|Page

fprintf(stdout,"%-8s %7d %8.2f %8d %11.2f\


n",item,number,price,quantity,value);
}
fclose(fp);
getch();
}
Output:
Input file name:
sastry
Input inventary data
itemname number price quantity
soap 100 36 20
dettol 101 76 15
pen 102 25 50

itemname number price quantity value


soap 100 36.00 20 720.00
dettol 101 76.00 15 1140.00
pen 102 25.00 50 1250.00

Another example

/*usage of fprintf,fscanf functions....*/


#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;
char name[20],filename[20];
clrscr();
printf("enter file name:");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("enter ur name: \n");
fscanf(stdin,"%s ",name); /* reading data from keyboard(stdin) */
fprintf(fp,"hai %s",name); /* printing data into file */
printf("hai %s",name); /* printing data into console(monitor)*/
fclose(fp);
getch();
}
Output:
enter file name: sastry.c
enter ur name:
ezrasastry ^Z
hai ezrasastry
hint: u can observe output in sastry.c file also
9|Page

Error handling during I/O operations

Refer in nodes..
Refer all programs

fputs, fgets functions

Refer in notes…
Example profram:
#include <stdio.h>
int main ()
{
FILE *fp; char str[60];
clrscr();
fp = fopen("file.txt", "w");
fputs("This is c programming.", fp);
fclose(fp);

fp = fopen("file.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
if(fgets (str,60,fp)!=NULL )
{
/* writing content to stdout */
printf("%s",str); /* we can write puts(str);*/
}
fclose(fp);

return(0);
}
Output:
This is c programming.

GETS, PUTS functions

Refer in notes…

Example program

#include<stdio.h>
#include<conio.h>
void main()
{
char n[10];
clrscr();
10 | P a g e

printf("enter some text: ");


gets(n); /this is used instead of scanf() function*/
printf("\n");
puts(n); /*this is used instead of printf() function*/

getch();
}
Output:
enter some text: hai this we are from nec, ece.b
hai this we are from nec, ece.b

Random access to files

Refer in nodes..
Refer all programs.

Binary files and Random Access files

You can jump instantly to any structure in the file in random access files.You can
change the contents of a structure anywhere in the file at any time.

Once one opens a file one can read, write, or seek any arbitrary structure in the file. C
maintains a "file pointer" to enable these functions. When the file is opened, the pointer
points to record 0 (the first record in the file). Any read operation reads the currently pointed-
to structure and moves the pointer to the next record or structure. A write is done at the
currently pointed-to structure and moves the pointer down one structure. Seek moves the
pointer to the specified record.
There are three new functions in the example code , i.e., fread, fwrite, fseek,
ftell,rewind
The fread function takes four arguments:
* A memory address
* The number of bytes to read per block
* The number of blocks to read
* The file variable

Syntax is

fread(&struct, sizeof(struct), no.of records, file pointer );

The fwrite function works the same way, but moves the block of bytes from memory to the
file.

fwrite(&structure,sizeof(struct),no of records ,filepointer)

The fseek function moves the file pointer to an arbitrary byte in the file. You can use three
options when seeking:
* SEEK_SET - moves the file pointer down from the beginning of the file, i.e. from byte
0.
* SEEK_CUR - moves the file pointer down from its current position.
* SEEK_END - moves the file pointer up from the end of file. Note you must use
negative offsets.
ftell() takes a file pointer and returns a number of type long, that corresponds to the current
position. This function is useful in saving the current position of a file.
n=ftell(fp);
11 | P a g e

n would give the relative offset of the current position. This means that ‘n’ bytes have already
been read.

rewind() takes file pointer and resets the position to the start of the file.
rewind(fp);
n=ftell(fp);
This would assign 0 to n because the file position has been set to the statement of the file by
rewind.

Example:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[] = "this is sample file";
char buffer[20];
/* Open file for both reading and writing */
fp = fopen("file.txt", "wb+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
/* Seek to the beginning of the file */
fseek(fp, SEEK_SET, 0);
/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp); // read from file
printf("%s\n", buffer); // output
fclose(fp);
return(0);
}
Output: this is sample file.

Using Command Line

Q1 Write a C program to print the table of a entered/ inputted


number. The output to be stored in file.

Q2 Write a C program to input a number, find its factorial. The


output to be stored in a file

Q3 Write a C-program to write the total marks and the name of a


student in a output file. After this open this file and read the name
12 | P a g e

and total marks and display the same on the monitor of your
computer.

You might also like