Home > Net >  How to read Line by line recursively?
How to read Line by line recursively?

Time:12-05

I want to make a recursive function which read a single line from a data the on the next recursion the next line.

i've tried using fgets but only read the first line of the data`

 void show_data_recursive(){
> file=fopen("Data Gaji Berdasarkan Daerah.dat", "r");
> char output[50];
> while(fgets(output, 50,file)!=NULL){
> puts(output);
> return show_data_recursive();
>   }
> return ;
> 
> }
> int main(){
> show_data_recursive();
> 
> }

CodePudding user response:

The problem in your code is that you re-open the same file again and again in each function call. Thus, you will always read the same portion of the file: the first line. What you want to do instead is to open it once in main and pass this opened file reference to the function you have:

void show_data_recursive(FILE* file){
    char output[50];
    // We can simply use an if here, no need for a while
    if (fgets(output, 50, file) != NULL) {
        puts(output);
        return show_data_recursive(file);
    }
}

int main(){
    FILE* file = fopen("Data Gaji Berdasarkan Daerah.dat", "r");
    if (file != NULL) {
        show_data_recursive(file);
        fclose(file);
    }
}

You should be careful when using recursion in C, by default the compiler will not optimize the calls (compile option -O0 or -Og for example). Which means that if you have a lot of lines in your file, you may trigger a stack overflow.

If you are using an optimization compile option such as -O2 (maybe -Os too), it will be able to perform a tail-call for your function and you won't have this issue. In fact, if the compiler can perform a tail-recursion, it means that you can easily convert your function into a loop, you may want to do this instead.

  •  Tags:  
  • c
  • Related