How to pass a .txt filet to a function



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

    File sending to function: funcaoRecebeArquivo(arquivo);

    I'm not sure what should be placed inside the parentheses when I call the function and send the file. A code outline 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;
    

    }



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

    No main when you call the function you have to pass the file that 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 you will normally use http://www.cplusplus.com/reference/cstdio/fread/ or http://www.cplusplus.com/reference/cstdio/fgets/ , whereas to write the most common is http://www.cplusplus.com/reference/cstdio/fwrite/ .




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2