Open a file using secondary function

1

I need to create a function that "points" a file pointer to a particular file in the computer's 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 left blank. The "fprintf" message is not recorded.

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 this really happened. The terminal was locked during execution.

    
asked by anonymous 02.09.2015 / 15:49

1 answer

4

The problem is not the open or write function in the file, but the reference parameter passing by which it is trying to do. The arq variable is a pointer to a file, and when passing a pointer as a parameter by reference it is necessary to use pointer to pointer at the end of count arq has an address. You can do it in 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!");

}
    
02.09.2015 / 18:27