Skip to main content

How to read nth line of a text file in C programming using file handling?

C program to read the nth line of a file. 



This file handling C program illustrates how to read the nth content of a text file. 

Suppose your text filename is "documents.txt" and you want to read only 9th line of that file. Here's a source code to do so.


  1. #include <stdio.h>
  2. int main()
  3. {
  4. FILE* file = fopen("documents.txt", "r");
  5. char line[256];
  6. int i = 0;
  7. while (fgets(line, sizeof(line), file)) {
  8. i++;
  9. if(i == 9 )
  10. {
  11. printf("%s", line);
  12. }
  13. }
  14. fclose(file);
  15. return 0;
  16. }


Similarly if you want to read only the 1st/2nd/3rd/4th/5th or any other line then just run variable i till your desired line.  

For example if i  want to read the 10th line of the same file

    if(i == 10 )
  1. {
  2. printf("%s", line);
  3. }


Comments