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.
- #include <stdio.h>
- int main()
- {
- FILE* file = fopen("documents.txt", "r");
- char line[256];
- int i = 0;
- while (fgets(line, sizeof(line), file)) {
- i++;
- if(i == 9 )
- {
- printf("%s", line);
- }
- }
- fclose(file);
- return 0;
- }
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 )
- {
- printf("%s", line);
- }
Comments
Post a Comment