FILE Handling notes
FILE Handling notes
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:
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.
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.
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+")
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.
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.
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
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).
c = getc(fp);
reads the next character from the file referenced by fp and the statement
putc(c,fp);
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 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");
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
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 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
Another example
Refer in nodes..
Refer all programs
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.
Refer in notes…
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
char n[10];
clrscr();
10 | P a g e
getch();
}
Output:
enter some text: hai this we are from nec, ece.b
hai this we are from nec, ece.b
Refer in nodes..
Refer all programs.
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
The fwrite function works the same way, but moves the block of bytes from memory to the
file.
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.
and total marks and display the same on the monitor of your
computer.