442 Programming and Data Structures
Explanation In the above program w hile statement is used for checking the end of file. The file
pointer is initially positioned at the beginning of the file and the whole text is printed.
To reposition the file pointer the statement f seek () is used. The file pointer is to be positioned at
nth character from the beginning of the file and the characters from nth position onwards will be
printed on the screen.
In the above program one can use the statement f seek (fp, -n, SEEK_END) in place of
f seek (fp, n, SEEK_SET) to read from backward direction from the end of file.
13.22 Write a program to read last few characters of the file using fseekO statement
# include <dos.h>
# include <stdio.h>
# include <conio.h>
void m&inO
{
FILE *fp;
in t n,ch;
c l r s c r { ) ;
fp=fopen(“text.txt","r")i
printf ("nContents offilen");
while ((ch*fgetc(fp))teEOF)
printf ("% c"^ h );
printf ( “
Hoxo many characters including spaces would you like to skip ?
scanf ('y 0d",&n);
fseek(fp^t-2rSEEK_END);
printf( “
Last %d characters ofaftlen",~l *n);
while ((ch=fgetc(fp))l=EOF)
printf ( u%c",ch);
fclose(fp):
)
Q U m i J ;
How many characters including spaces would you like to skip ?: 5
Last 5 characters of a file
WORLD
Explanation The statement f seek (fp ,n - 2, SEEK END) depositions the file pointer n-2 bytes in the
backward directions from the end of file. With this statement last characters of a statement can be
printed on the screen i.e. printing information will be from the position till the end of file. Here the
value of 'n ' entered is 5. To skip the account of NULL character and space decimal number 2 is
subtracted from n. Thus, we get the output WORLD.
13.23 Write a program to display V program files in current directory. The user should
select one of the files. Convert the file contents in capital and display the same on the
screen. Also calculate total characters and lines.
# include <ctype.h>