Answers
The soluion for the given question is given below with screenshot of output.
-------------------------------------------------------------------------------------------------------------------------------------
I have kept the logic simple and added comments for understandiing i have used system call in the program
If there is anything else let me know in comments
Input File use : textfile.txt
The Lion and the Mouse Once when a lion, the king of the jungle, was asleep,
a little mouse began running up and down on him. This soon awakened the lion,
who placed his huge paw on the mouse, and opened his big jaws to swallow him.
"Pardon, O King!" cried the little mouse. "Forgive me this time. I shall never
repeat it and I shall never forget your kindness. And who knows, I may be able
to do you a good turn one of these days!The lion was so tickled by the idea
of the mouse being able to help him that he lifted his paw and let him go.
Sometime later, a few hunters captured the lion, and tied him to a tree.
After that they went in search of a wagon, to take him to the zoo.Short
StoriesJust then the little mouse happened to pass by.
On seeing the
lion’s plight, he ran up to him and gnawed away the ropes that bound him,
the king of the jungle."Was I not right?" said the little mouse, very
happy to help the lion.
MORAL: Small acts of kindness will be rewarded greatly.
-------------------------------------------------------------------------------------------------------------------------------------
-------- CODE TO COPY ----------------------------------------------------------------------------------------------------
/*
* fpart is a command to show the part of a test file.
* USAGE : ./fpart text-file-name start-byte <end-byte>
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if ( argc < 3 )
{
printf("Too less parameters\n");
printf("usage fpart filename start [end]\n");
return 1;
}
// file name is stored in filename
// display file start at start byte
// display file end at end byte
char filename[32] = "";
int start = 0;
int end = 0;
char buf;
strcpy( filename, argv[1] );
if ( strstr(filename, ".txt") == NULL )
{
printf("Input file not a text file\n");
return 1;
}
start = atoi( argv[2] );
if ( argc == 4 )
end = atoi( argv[3] );
int fp = open(filename, O_RDONLY);
if ( fp == -1 )
{
printf("Error opening file for reading [%s]\n",filename);
return 1;
}
// Reading the file byte by byte
int bytes_read = 1;
while ( read( fp, &buf, 1) != 0 ){
// if start byte is found start printing
if ( bytes_read >= start )
printf("%c",buf);
// if end byte is found stop printing
if ( end != 0 && bytes_read > end )
break;
bytes_read++;
}
printf("\n");
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------
Output :