How can I open a file in a void function?

0

I am trying to open a text file in a int abreArquivoEntrada function, and for this I am sending as a parameter the pointer of type FILE and a vector of char containing the file name, within the function I use to function of fopen , but when I start the file pointer after the function execution, it has not changed.

Thank you in advance.

#include <stdio.h>
#include <stdlib.h>

struct PESSOA{
    char nome[50];
    int idade;
    float altura;
};

void leNomeArquivoEntrada(char* S1){
    printf("Nome do arquivo: ");
    scanf("%s",S1);
}

int abreArquivoEntrada(FILE *Arq , char* S1){

    Arq = fopen(S1,"r");

    printf("Na funcao %d \n", Arq);

    if(Arq == NULL)
        return 0;
    else
        return 1;

}

void fechaArquivo(FILE *Arq){

    fclose(Arq);
}

int main()
{
   char S1[50], inf[50];

    struct PESSOA Povo[10], P;
    FILE *Arq;
    int i;

    leNomeArquivoEntrada(S1);

    printf("Na main antes da bertura %d \n", Arq);


    if(abreArquivoEntrada(Arq, S1) == 1){


        printf("Na main %d \n", Arq);
        fscanf(Arq,"%s", &P.nome);
        fscanf(Arq,"%d", &P.idade);
        fscanf(Arq,"%f", &P.altura);
        printf("%s \n", P.nome);
        printf("%d \n", P.idade);
        printf("%f \n", P.altura);



        fechaArquivo(Arq);

    }
    else printf("Erro na abertura do arquivo");

    return 0;
}
    
asked by anonymous 03.03.2018 / 21:47

1 answer

2

In C the parameters are passed by copy. If you want to change the value in the function you can pass the address of the value you want to change, rather than the value itself. In your case you would have to send to the function the address of the FILE* you have, using & :

if(abreArquivoEntrada(&Arq, S1) == 1){
//--------------------^

The function then has to get a pointer of FILE* or a FILE** .

Making the respective settings in the function would look like this:

int abreArquivoEntrada(FILE **Arq , char* S1){
//--------------------------^ duplo ponteiro agora

    *Arq = (fopen(S1,"r")); //*Arq em vez de Arq

    if(*Arq == NULL) //*Arq em vez de Arq
        return 0;
    else
        return 1;
}

The exchange was almost based on% change from% to% with%.

A common alternative is to return the new value you want for the pointer, however since it was already using a return of Arq this solution was rendered unfeasible.

I recommend that you also read my response to the subject that will help you better understand why:   # 220063 "> Pointer pointer to change my stack. Why should I use them?

    
03.03.2018 / 23:14