I am trying to write a program which read the file and print lines from line#30 to line#50 but not able to achieve it.
main() {
FILE *fp;
char ch;
int nol = 0;
fp = fopen ("test.txt","r");
while (1){
ch = fgetc(fp);
if (ch == '\n')
nol++;
if (nol > 30 || nol < 50){
printf ("value of NOL is %d\n", nol);
}
if (ch == EOF)
break;
}
fclose (fp);
printf ("\nNumber of line in file: %d\n", nol);
I tried with if nol >=30 and nol <=50 condition and tried to print but that is not working. Any input will be of great help.
First, the logic part.
Generally we think of line numbers as beginning at 1 instead of 0. So initialise
nolto 1.If you want to display lines 30 to 50, then you need to include them in the test. Use
>=instead of>(same for<).And of course you need to use
&&instead of||, otherwise your condition is always true.If you want to actually display the lines, you need something like this:
Note the order of the statements.
But really, you should look at using
fgetsif you want to display the lines, instead of reading one character at a time.