Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the next line of a file every time a function is called

Tags:

c

file-io

I have a text file with numbers on each line. I want to write a function in C that reads in the file and returns the next number in the file every time the function is called.

For example if I have these numbers:

100 
200 
300 
400

and a function called get_number(), if I call get_number() it will return 100, if I call it again, it will return 200, etc.

This is what I've written so far but every time the function is called, it always goes back to the first number in the text file.

int * get_number()
{

    FILE* file = fopen("random_numbers.txt", "r");
    char line[256];

    if (file==NULL) 
    {
        perror ("Error reading file");
    }
    else
    {
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }

    return 0;
}
like image 320
lye090 Avatar asked Dec 20 '25 03:12

lye090


1 Answers

here's a version that does exactly that :

 int * get_number(long* pos)
{

    FILE* file = fopen("random_numbers.txt", "r");
    char line[256];

    if (file==NULL) 
    {
        perror ("Error reading file");
    }
    else
    {
        fseek(file , *pos , SEEK_CUR);
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }
    *pos = ftell(file);
    return 0;
}

and you call it from main like this

long pos = 0;
get_number(&pos);

or better yet use a static variable

 int * get_number()
{
    static long pos = 0;
    FILE* file = fopen("random_numbers.txt", "r");
    char line[256];

    if (file==NULL) 
    {
        perror ("Error reading file");
    }
    else
    {
        fseek(file , pos , SEEK_CUR);
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }
    pos = ftell(file);

    return 0;
}
like image 89
Farouq Jouti Avatar answered Dec 21 '25 18:12

Farouq Jouti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!