rewind():
It is the function which sends the file pointer to the
beginning of file.
It is mostly used when file is opened in write/read mode or
append/read mode.
It accepts the file pointer as argument.
Function definition:
void rewind(FILE *p)
{
--------------------------
--------------------------
--------------------------
}
Specification3:
Write a program to copy the contents of "nice1"
onto "nice2" (copy) and display the contents of "nice2"
Program:
#include<stdio.h>
void main()
{
FILE *p,*q;
char ch;
clrscr();
p=fopen("nice1","r"); /* opened in read mode */
q=fopen("nice2","w+"); /* opened in write/read mode */
while(1)
{
ch=fgetc(p); /*
reading from "nice1" */
if(ch==-1)
break;
fputc(ch,q); /*
writing onto "nice2" */
}
printf("File
is copied\n");
fclose(p);
/* closing "nice1" */
printf("The
contents of target file:\n");
rewind(q);
/* sends the file pointer to BOF */
while(1)
{
ch=fgetc(q); /*
reading the data of "nice2" */
if(ch==-1)
break;
printf("%c",ch); /*
printing onto monitor */
}
fclose(q);
/* closing "nice2" */
getch();
}
Execution:
File is copied
The contents of target file:
Nice informatics
Kavali
pin: 524201
Program explained:
1. "nice1" is opened in read mode.
2. "nice2" is opened in write/read mode
3. "nice1" is copied onto "nice2"
character by character until the end of file.
4. File pointer of "nice2" is set to the beginning
of file using rewind() function.
5. Contents of "nice2" are displayed as output.
Specification4:
Append the data to the file "nice1" and display
the total contents of file.
Note: Adding at the tail is called append.
Program:
#include<stdio.h>
void main()
{
FILE *p;
char ch;
clrscr();
p=fopen("nice1","a+");
printf("Enter
the text:\n");
while(1)
{
ch=getchar();
if(ch==-1)
break;
fputc(ch,p);
}
rewind(p);
printf("Contents
of file:\n");
while(1)
{
ch=fgetc(p);
if(ch==-1)
break;
printf("%c",ch);
}
fclose(p);
getch();
}
Execution
Enter the text:
Do whatever you have to do..
Whether you like it or not...
^Z
Contents of file:
Nice informatics
Kavali
pin: 524201
Do whatever you have to do..
Whether you like it or not...
Program explained:
The file is opened in append/read mode.
Additional data is added at the end of file.
Sent the file pointer to the beginning of the file
Finally, printed the total file.
0 comments:
Post a Comment