How to pass a .txt file to a function

1

I would like to create a function that receives a .txt file and does something with it, but I do not know how to set the send and receive parameters, or if I should do parameter passing by reference.

Send file to function: funcaoRecebeArquivo(arquivo);

I'm not sure what to put inside the parentheses when I call the function and send the file. An outline of code below:

funcaoRecebeArquivo(arquivo)
{
    //Receber o arquivo e fazer algo com ele aqui dentro
}

int main ()
{

    FILE *sensvalid;

    if ((sensvalid = fopen("X10Map.txt","r")) == NULL) 
    {
        printf("Nao consegui abrir o arquivo X10MAP.");
        return 2;
    }

    funcaoRecebeArquivo(arquivo);
    return 0;
}
    
asked by anonymous 09.12.2017 / 00:18

1 answer

2

The function that receives the file must receive a parameter of type FILE* , and will usually be of type void unless you want to return a specific value for main .

No main when calling the function must pass the file that opened for reading, which in your case is sensvalid .

Code example with this structure:

void utilizarArquivo(FILE *arquivo)
{
    //fazer qualquer coisa com o arquivo, como por exemplo fread()
}

int main ()
{

    FILE *sensvalid;

    if ((sensvalid = fopen("X10Map.txt","r")) == NULL) 
    {
        printf("Nao consegui abrir o arquivo X10MAP.");
        return 2;
    }

    utilizarArquivo(sensvalid);//o parametro a passar é sensvalid, que representa o arquivo
    return 0;
}

To read information from the archive you will usually use fread or fgets , while writing the most common is fwrite .

    
09.12.2017 / 00:50