How to pass an file . txt to a function

Asked

Viewed 2,132 times

1

I would like to create a function that receives a file .txt and do something with it, but I don’t know how to define the sending and receiving parameters, or if I should pass parameter by reference.

Sending the file to function: funcaoRecebeArquivo(arquivo);

I’m not sure what should be placed inside the parentheses when calling the function and sending the file. A code sketch 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;
}
  • Your question is how to define the header of the function that receives the file ? If so it would be something like void funcaoRecebeArquivo (FILE *arquivo)

  • Exactly, I also need to call the function inside the main.

1 answer

2


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

In the main when calling the function you have to pass the file you opened for reading, which in your case is the sensvalid.

Example of code 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 file information will normally use fread or fgets, whereas to write the most common is fwrite.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.