File handling in linked lists (c99)
19:57 23 Feb 2026

I'm a college student, and I'm trying to figure out how to file handle in linked list or at least know if that's possible. Here's what i've been doing:

#include 
#include 

typedef struct node{

    int num;
    FILE* arq;
    struct node* next;

}node;


node* createnode(int x, char* argv){

    node* head = (node*)malloc(sizeof(node));

    head->next = NULL;
    head->num = x;
    head->arq = fopen(argv, "r");

}

void addtoend(node** head, int x, char* argv){

    node* new = createnode(x, argv);

    node* n = *head;

    while (n->next != NULL) n = n->next;

    n->next = new;

}

void freeeverything(node** head){

    node* n = *head;
    node* aux = *head;
    
    while (n!= NULL) {
        fclose(n->arq); 
        n = n->next;
        free(aux);
        aux = n;
    }
}



int main(int argc, char* argv[]){


    FILE* Z;

    node* head = NULL;
    head = createnode(1, argv[1]);
    node* n = head;
    for (int i = 2; i < argc; i++) addtoend(&head, 2, argv[i]);
    int a[2][2];
    int b[2][2];
 



    fscanf(n->arq,"%d %d", &a[0][0], &a[0][1]);
    fscanf(n->arq,"%d %d", &a[1][0], &a[1][1]);
    n = n->next;
    fscanf(n->arq,"%d %d", &b[0][0], &b[0][1]);
    fscanf(n->arq,"%d %d", &b[1][0], &b[1][1]);
    

    printf("%d %d %d %d\n", b[0][0]*a[0][0], b[0][1]*a[0][0], b[0][0]*a[0][1], b[0][1]*a[0][1]);
    printf("%d %d %d %d\n", b[1][0]*a[0][0], b[1][1]*a[0][0], b[1][0]*a[0][1], b[1][1]*a[0][1]);
    printf("%d %d %d %d\n", b[0][0]*a[1][0], b[0][1]*a[1][0], b[0][0]*a[1][1], b[0][1]*a[1][1]);
    printf("%d %d %d %d\n", b[1][0]*a[1][0], b[1][1]*a[1][0], b[1][0]*a[1][1], b[1][1]*a[1][1]);



    Z = fopen("tusao_Z.txt", "w+");

    fprintf(Z,"%d %d %d %d\n", b[0][0]*a[0][0], b[0][1]*a[0][0], b[0][0]*a[0][1], b[0][1]*a[0][1]);
    fprintf(Z,"%d %d %d %d\n", b[1][0]*a[0][0], b[1][1]*a[0][0], b[1][0]*a[0][1], b[1][1]*a[0][1]);
    fprintf(Z,"%d %d %d %d\n", b[0][0]*a[1][0], b[0][1]*a[1][0], b[0][0]*a[1][1], b[0][1]*a[1][1]);
    fprintf(Z,"%d %d %d %d\n", b[1][0]*a[1][0], b[1][1]*a[1][0], b[1][0]*a[1][1], b[1][1]*a[1][1]);


    fclose(Z);


    freeeverything(&head);

    return 0;

}

I'm aware that there are better ways to print all these stuff. I just like to start like that so i can better visualize my code. The error itself appears after the first fscanf: Exception has occurred. Segmentation fault. And I just can't seem to find the problem. I have been testing with two text files:

matrix_A.txt

1 2
3 4

matrix_B.txt

0 5
6 7

And this is the expected output:

0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
c linked-list file-handling argv argc