Saturday 31 August 2013

Closing the File | C Programming Language Pdf



Closing the File:

The input output library supports the function to close a file; it is in the following format.
f close(file -'pointer);
A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.

Observe the following program ..
FILE *p 1 *p2;
Pl = fopen ("Input","w");
p2 = fopen ("Output" ,"r");
……
……
fclose(p1); fclose(p2)

The above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.
Reading a character from a file and writing a character into a file ( getc () and putc ()' functions)
The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fpl); similarly getc function is used to read a character from a file that has been open in read mode.
c=getc(fp2).
The program shown below displays use of a file operations. The data enter through the keyboard and the program- writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

Sample program for using getc and putc functions*/.:
#include< stdio.h >
void mainO
{
FILE *fl;
printf("Data input output");
fl =fopen("Input","w"); /*Open the file Input*/
while«c=getcharO)!=EOF) /*get a character from key board*/
putc( c,fl); /*write a character to input* /
fclose(fl); /*close the file input* / printf("Data output");
fl =fopen("INPUT" ,"r"); /*Reopen the file input* /
while« c=getc(fl ))!=EOF)
printf("%c",c );
fclose(fl );
}

4. Reading a integer from a file and writing a integer into a file ( getw() and putw() functions)
These are integer-oriented functions. They are similar to get c 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 forms of getw and putw are:
putw(integer,fp );
getw(fp);

/*Example program for using getw and putw functions * 
/ #include< stdio.h >
void main( )
{
FILE *fl, *f2, *f3;
int number,i;
printf("Contents of the data filenn");
fl =fopen("DA T A","W");
for(i=l;i< 30;i++)
{
printf("enter the number");
scanf("%d" ,&number);
if(number= =-l)
break;
putw (number,fl );
}
fclose(fl);
fl =fopen("DA T A","r");
f2=fopen("ODD", "w");
f3 =fopen ("EVEN", "w");
while((number=getw(fl))!=EOF)/* Read from data file*/
{
if(number%2=0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(fl );
fclose(f2);
fclose(f3);
f2=fopen("O DD" ,"r");
f3 =fopen("EVEN", "r");
printf("nnContents of the odd filenn");
while(number=getw(f2))! = EO F)
printf("%d" ,number);
printf("nnContents of the even file");
while(number=getw(f3))! = EPF)
printf("%d" ,number);
fclose(f2);
fclose(f3);
}

5. fscanf() and fprintf() functions:
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is fprintf(fp,"control string", list);
Where fp id a file pointer associated with a file that has been opened for writing. The control string is fiJe output specifications list may include variable, constant and string.
fprintf(fl ,%s%d%f",name,age,7 .5);
Here name is an array variable of type char and age is an int variable
The general format of fscanf is fscanf(fp,"controlstring" ,list);
This statement would cause the reading of items in the control string.

Example:
fscanf( fL,"5 s%d" ,item, & quantity");
Like scanf, fscanf also returns the number of items that are successfully read.
*Program to handle mixed data types*
#include< stdio.h >
main()
{
FILE *fp;
int num,qty,i;
float price,value;
char item[10],
flemupe[10];
printf("enter the filename");
scanf("%s" ,filename);
fp=fopen( filename, "w");
printf("Input inventory data");
printf("Item namem number price quantity");
for (i=l;i< =3;i++)
{
fscanf( stdin, "%s%d %f%d" ,item,&number ,&price,&quality);
fprintf( fp, "%s%d%fl,lod" ,itemnumber, price, quality );
}
fclose (fp);
fprintf( stdout, "nn");
fp=fopen( filename, "r");
printf ("Item name number price quantity value");
for(i=l;i< =3;i++)
{
fscanf( fp, "%s%d %f1l,lod" ,item, &number ,&prince, &quality);
value=price*quantity;
fprintf("stdout, "%s%d%f1l,lod %dn" ,item, number ,price, quantity , val ue);
} fclose(fp );
}

6. fgetc () and fputc() functions:
fgetc() function is similar to getc() function. It also reads a character and increases the file pointer position. If any error or end of the file is reached it returned EOF.
fputc() function writes the character to the file shown by the file pointer. It also increases the file pointer position.
Sample program to write text to a file using fputc() and read the text from the same file using fgetc()
#include<stdio.h>
void main()
{
FILE *fp; char c;
fp=fopen("lines. txt", "w");
while( ( c=getcharO 1 =' *.') fputc( c,fp);
fclose(fp);
fp=fopen("lines. txt" ,"r");
while(( c=fgetc(fp ))!=EOF) printf("%c",c );
fclose(fp);
}

7. fgets() and fputs() functions:
fgets() function reads string from a file pointed by file pointer. It also copies the string to a memory location referred by an array.
fputs() function is useful when we want to write a string into the opened file .
Sample program to write string to a file using fputs() and read the string from the same file using fgets()
#include<stdio .h> void main()
{
FILE *fp;
Char file [ 12],text[ 50];
fp = fopen("line. txt" ,"w");
printf("enter text here ");
scanf("%s" , te~t); fputs(text,fp );
fclose( fp );
fp = fopen("line. txt", "r");
if(fgets(text,50,fp )!=NULL)
while(text[i] !='\O')
{
putchar(text[i]);
i++;
}
fclose(fp );
getch();
}

8. fread() and fwrite () functions
You can regard an array, or an array of structured variables, as simply a block of memory of a particular size. The input/output routines provide you with routines that you can call to drop a chunk of memory onto a disk file with a single function call.
However, there is one thing you must remember. If you want to store blocks of memory in this way the file must be opened as a binary file. What you are doing is putting a piece of the program memory out on the disk. You do not ~ow how this memory is organised, and will never want to look at this, so you must open the file as a binary file. If you want to print or read text you use the fprintf or scanf functions.
The function fwrite sends a block of memory out to the specified file. To do this it needs to know three things; where the memory starts, how much memory to send, and the file. to send the memory to. The location ofthe memory is just a simple pointer, the destination is a pointer to a FILE which has been opened previously, the amount of memory to send is given in two parts, the size of each chunk, and the number of chunks. This might seem rather long wjnded, but is actually rather sensible. Consider:
typedef struct {
char name [30] ;
char address [60] ;
int account ;
int balance ;
int overdraft ;
} customer;
customer Hull_Branch [100] ;
FILE * Hull_File;
fwrite ( Hull_Branch, sizeof ( customer), 1 00, Hull_File) ;

The first parameter to fwrite is the pointer to the base of the array of our customers.
The second parameter is the size of each block to save. We can use sizeof to find out the size of the structure. The third parameter is the number of customer records to store, in this case 100 and the -final parameter is the file which we have opened. Note that if we change the number of items in the customer structure this code will still work, because the amount of data saved changes as well.
The opposite of fwrite is fread. This works in exactly the same way, but fetches data from the file and puts it into memory:
fread ( Hull_Branch, sizeof ( customer), 1 00, Hull_Data) ;
If you want to check that things worked, these functions return the number of items that they transferred successfully:
if( fread (Hull_Branch, sizeof( customer), 100, Hull_Data) < 100) {
printf ( "Not all data has been read!\n\n" ) ; }
}

Sample program using fread() and fwrite() functions
#include<stdio.h>
struct student
{
char name[20];
int age;
}stud[5];
void main()
{
FILE *fp;
int i,j=0,n;
char str[15];
fp=fopen("line. txt" ,"rb");
printf("enter the number of records");
scanf("%d",n);
for(i=O;i<n;i++ )
{
scanf("%s",stud[i] .name);
scanf("%d",stud[i] .age);
}
}
whileG<n)
{
fwrite( &stud,size( stud), 1 ,fp);
j++;
}
}
fclose(fp );
fp=fopen ("line. txt", "r");
j=0;
while(j<n)
{
fread( &stud,sizeof( stud), 1 ,fp);
printf("%s %d" ,stud[j] .name,stud[j] .age);

fclose(fp ); 
}

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved