C program to read a range of bytes from file and print it to console
Last Updated :
28 Jun, 2021
Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console.
Functions Used:
- fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.
- fgetc(): Reading the characters from the file.
- fclose(): For closing a file.
Approach:
- Initialize a file pointer, say File *fptr1.
- Initialize an array to store the bytes that will be read from the file.
- Open the file using the function fopen() as fptr1 = fopen(argv[1], “r”).
- Iterate a loop until the given file is read and stored, the characters are scanned in the variable, say C using the fgetc() function.
- Store each character C extracted in the above step, to a new string S and print that string using the printf() function.
- After completing the above steps, close the file using the fclose() function.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
int main( int argc, char * argv[])
{
FILE * fptr1;
char c;
char str[MAX];
int i = 0, j, from, to;
fptr1 = fopen (argv[1], "r" );
if (fptr1 == NULL) {
return 1;
}
printf ( "Read bytes from: " );
scanf ( "%d" , &from);
printf ( "Read bytes upto: " );
scanf ( "%d" , &to);
for (i = 0, j = 0; i <= to
&& c != EOF;
i++) {
if (i >= from) {
str[j] = c;
j++;
}
c = fgetc (fptr1);
}
printf ( "%s" , str);
fclose (fptr1);
return 0;
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...