Close a file with close() and I can't make it work

70 views Asked by At

In my program I keep a list of opened files, and when I call close, it does not close the file descriptor that I pass to it, but rather the one with the highest number. I attach the code:

bool closeFd(List *fileList, int position)
{
    Pos p;

    p = findPosition(position, *listaFicheros);

    if (close(p->data.fileDescriptor) == (-1)) 
    {
        perror("File non-existent");
        return false;
    }
    else
    {

        deleteAtPosition(p, fileList);
        return true;
    }
}

Those are my outputs:

(The command close [fd] closes the file related to the file descriptor, example: close 2 -> should close standard error. And if it is an invalid file descriptor, the perror message should pop up. My problem is that when I put an fd higher than the possible, it closes the last file opened)

> open try.txt cr
Added entry 3 to the open files table
-> open try2.txt tr
Added entry 4 to the open files table
-> open
descriptor: 0 -> standard input
descriptor: 1 -> standard output
descriptor: 2 -> standard error 
descriptor: 3 -> try.txt O_CREAT
descriptor: 4 -> try2.txt O_TRUNC
-> close 8
-> open
descriptor: 0 -> standard input
descriptor: 1 -> standard output
descriptor: 2 -> standard error 
descriptor: 3 -> try.txt O_CREAT
-> close 6
-> open
descriptor: 0 -> standard input
descriptor: 1 -> standard output
descriptor: 2 -> standard error 
-> close 9 
-> open
descriptor: 0 -> standard input
descriptor: 1 -> standard output
-> 

I have checked with gbd and the file descriptor that is passed to close is correct

This is the function findPosition:

Pos findPosition(int position, List L)
{
    Pos p;

    p = L;
    while (p->data.position != position && p->next != NULL)
        p = p->next;
    
    return p;
}

This is deleteAtPosition:

void deleteAtPosition(Pos p, List *L)
{
    Pos q;

    if (p == *L)
        *L = (*L)->next;
    else if (p->next == NULL)
    {
        q = previous(p, *L);
        q->next = NULL;
    }
    else
    {
        q = p->next;
        p->data = q->data;
        p->next = q->next;
        p = q;
    }
    free(p);
}

This is previous:

Pos previous(Pos p, List L)
{
    Pos q;
    if (p == L)
        return NULL;
    else
    {
        for (q = L; q->next != p; q = q->next)
            ;
        return q;
    }
}

This is my .h for the list to make clear the types:

#define COMMAND_LENGTH 50

typedef char command[COMMAND_LENGTH];

typedef struct Item
{
    command name;
    int fileDescriptor;
    int position;
    int mode;
} Item;

typedef struct Node *Pos;
struct Node
{
    Pos next;
    Item data;
};
typedef Pos List;
0

There are 0 answers