TheQuack45

C Print Line Number Fixed

Jun 16th, 2016
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define FILE_MAX 255
  5.  
  6. int main ()
  7. {  
  8.     char fName[FILE_MAX];
  9.  
  10.     printf("Filename:\n");
  11.     fgets(fName, FILE_MAX, stdin);
  12.     fName[strcspn(fName, "\n")] = 0;
  13.  
  14.     FILE *ftc;
  15.     if ((ftc = fopen(fName, "r")) != NULL)
  16.     {  
  17.         printf("Number of line to read:\n");
  18.         int lnNum;
  19.        
  20.         while (scanf("%d", &lnNum) != 1 || lnNum <= 0)
  21.         {
  22.             printf("Please enter a valid, positive (>0) integer.\n");
  23.             printf("Number of line to read:\n");
  24.         }
  25.        
  26.         int il, c;
  27.         il = 1;
  28.        
  29.         while ((c = fgetc(ftc)) != EOF)
  30.         {
  31.             if (c == '\n')
  32.             {
  33.                 il++;
  34.             }
  35.             else if (il == lnNum)
  36.             {
  37.             printf("%c", c);
  38.             }
  39.         }  
  40.    
  41.         printf("\n");
  42.     }
  43.     else
  44.     {
  45.         printf("A file was not found with the specified name, or the file found could not be accessed for reading by the program.\n");
  46.     }
  47.    
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment