c - Read the next line of a file every time a function is called -
I have a text file with numbers in each row, I want to type the function in C which reads in the file and the function Every time in the function gives the next number. For example, if I have these numbers:
100 200 300 400 and get_number (), a function called, If I call get_number (), then it will return 100, if I call it again, then it will return 200, etc.
This is what I have written so far, but the function is called every time, it always goes to the first number in the text file.
int * get_number () {FILE * file = fopen ("random_numbers.txt", "r"); Four line [256]; If (file == NULL) {perror ("Error reading file"); } Other {fgets (line, size (line), file); printf ("% s", line); } Return 0; }
Here is a version that actually does: < pre> integer * get_number (long * position) {FILE * file = fopen ("random_numbers.txt", "r"); Four line [256]; If (file == NULL) {perror ("Error reading file"); } Else {fseek (file, * position, SEEK_CUR); Fgets (line, size (line), file); printf ("% s", line); } * pos = ftell (file); Return 0; } and you like it with main long position = 0; get_number (& amp; status); or better yet use a fixed variable
int * get_number () {static long = 0; FILE * file = fopen ("random_numbers.txt", "r"); Four line [256]; If (file == NULL) {perror ("Error reading file"); } And {fseek (file, position, SEEK_CUR); fgets (line, size (line), file); printf ("% s", line); } Pos = ftell (file); Return 0; }
Comments
Post a Comment