How can I open a file in a void function?

Asked

Viewed 151 times

0

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

Grateful from now on.

#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;
}
  • 1

    I could not understand what you want to do. You would like to display the contents of the file in the function leNomeArquivoEntrada(), would be this?

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 instead of the value itself. In your case you would have to send to the function the address of FILE* it has, using &:

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

The function now has to receive a pointer of FILE* namely a FILE**.

Making the respective adjustments to 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 based almost on change Arq for *Arq.

A common alternative is to return the new value you want to the pointer, however as you were already using a return int this solution was made impossible.

I recommend that you also read my answer on the subject that will help you understand better why: Pointer pointer to change my battery. Why should I use them?

  • Thank you Isac, your explanation helped me too.

  • @jaojpaulo I’m glad it was clear. We’re here to help.

Browser other questions tagged

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