[Solved] How to read line by line from file


As you saw, your function read_ins is always outputting the first line of your file program.txt.

This is because each time you open the file using fopen, the read cursor is starting from the beginning of the file.

To change this behavior, you should open the file and give the FILE* as an argument of your function read_ins and leave it open until the end of the main.

Something like:

int main(void)
{
    // Open file
    FILE *fptr;
    if ((fptr = fopen("program.txt", "r")) == NULL){
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }

    // Read Instructions (32bit)
    while (i<3){
        read_ins(fptr, ins);
    }

    // Close file
    fclose(fptr);

    return 0;
}


void read_ins(FILE* fptr, char ins[]){
    // reads text until newline
    fscanf(fptr,"%[^\n]", ins);
}

As the new read_ins is only one line, you can get rid of it…

Or, you can open and close the file in read_ins but you need to specify the number of the line you want to return. And read the file until you found the correct line. However, this is quite expensive as you open and close a file everytime..

solved How to read line by line from file