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

Popular posts from this blog

How to connect php to mysql database? Simple html comment box tutorial.

First thing first. You will need a little bit knowledge of web programming. Simple HTML will work. Now here is a step by step procedure on how to connect php to mysql database using local server. Lets create a simple comment box. And I will teach you how to do this on both Mac or windows/Linux. Here is a list of Applications you need before doing some coding. A text editor ( I would recommend Sublime text ) A local server software ( MAMP for mac , Xampp for windows/linux) Now that you have downloaded your local server software, install it and start the servers. If you are on mac follow the screenshot to start up the servers. Bravo ! Your computer is now a server (local though). If you are on windows/Linux follow the similar procedure to start your servers.  Now lets get into some simple coding. Since we are going to make a simple comment box, lets create two files "comment.php"and "comment_post.php" inside htdocs folder. Note : Your def...