Open a file using secondary function

Asked

Viewed 629 times

1

I need to create a function that "points" a file pointer to a particular file in computer memory. I was able to do this:

#include <stdio.h>

void abre(FILE*);
void procedimento();

int main ()
{
    procedimento();

    return 0;
}

void abre(FILE* arq)
{
    arq = fopen("testando.txt", "w");
}

void procedimento()
{
    FILE* arq = NULL;

    abre(arq);

    fprintf(arq, "Ola mundo!");

}

The program runs on the terminal, no errors occur. The file is created, but it is empty. "fprintf" message is not saved.

NOTE: First I was doing the code without pointing the file to NULL, however I read that errors occur when you use a pointer without pointing it to some memory address and it really happened. The terminal would crash during execution.

1 answer

4


The problem is not the opening or writing function in the file but the passing of parameter by reference that you are trying to do. The variable arq is a pointer to a file and when passing a pointer as a parameter by reference it is necessary to use pointer to end of accounts pointer arq has an address. You can do it two ways. Using pointer to pointer:

#include <stdio.h>

void abre(FILE** arq);
void procedimento();

int main ()
{
    procedimento();

}

void abre(FILE** arq)
{
    *arq = fopen("testando.txt", "w");
}

void procedimento()
{
    FILE* arq = NULL;

    abre(&arq);

    fprintf(arq, "Ola mundo!");

}

Or declaring arq as a global variable:

#include <stdio.h>

void abre();
void procedimento();
FILE* arq = NULL;

int main ()
{
    procedimento();

}

void abre()
{
    arq = fopen("testando.txt", "w");
}

void procedimento()
{

    abre(arq);

    fprintf(arq, "Ola mundo!");

}

Browser other questions tagged

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