C Programming - reading a specific line from a text file

Here is the code :

int main() { struct vinnaren { char vinnare[20]; int artal; }; struct vinnaren v[10]; int inputrader; int antalrader; //I want antalrader to be equal to the first //line in test.txt(the first line is "5") char file_name[256] = "test.txt"; char buf[512]; FILE *f = fopen(file_name, "r"); if (!f) { exit(0); } while (fgets(buf, sizeof buf, f)) { printf("%s", buf); } fclose(f); } 

This is the code I have. I want to make antalrader = line1 in the test.txt file. How did I read a specific line from the file?

+8
c file-io
source share
1 answer

With this code, you can read a file line by line and therefore read a specific line from a text file:

 lineNumber = x; static const char filename[] = "file.txt"; FILE *file = fopen(filename, "r"); int count = 0; if ( file != NULL ) { char line[256]; /* or other suitable maximum line size */ while (fgets(line, sizeof line, file) != NULL) /* read a line */ { if (count == lineNumber) { //use line or in a function return it //in case of a return first close the file with "fclose(file);" } else { count++; } } fclose(file); } else { //file doesn't exist } 
+12
source share

All Articles