1
Good evening, I’m having a problem in fopen function within a subroutine. This returning NULL. I could not identify the error because I am still beginner, if someone can help me. Note: I declared FILE *arq in global scope, I tried to change it into the main and also the function rcaracter(), but still keeps returning NULL and falling into the IF of the error message.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void rcaracter();
void rpalavra();
FILE *arq;
int main(void)
{
int i,opt;
char palavra[30];
do
{
printf("Programa:Arquivo\n");
printf("-Menu-\n");
printf("[1]-Arquivo Caracter\n");
printf("[2]-Arquivo Palavra\n");
printf("[3]-Sair\n");
printf("Opção:");
scanf("%d", &opt);
system("cls");
switch (opt)
{
case 1:
rcaracter();
break;
case 2:
break;
}
}while(opt != 3);
}
void rcaracter()
{
char caracter;
arq = fopen("arquivo.txt", "r+");
if(arq == NULL)
{
printf("Falha na abertura\n");
system("pause");
system("cls");
}
else
{
printf("Digite o caracter:");
scanf("%c", caracter);
fflush(stdin);
system("cls");
while (caracter != 'f')
{
fputc(caracter, arq);
if (ferror(arq))
{
printf("Falha na gravação\n");
system("pause");
system("cls");
}
else
{
printf("Sucesso!");
}
printf("Digite outro caracter ou 'f' para sair:");
scanf("%c", caracter);
}
}
fclose(arq);
}
can explain better what you are trying to do and maybe post content to your test file and the expected output?
– arfneto
Hard to answer without knowing exactly what the error is. To find the error, include the header
errno.h, and in the if that is returning NULL, change the message print toprintf("Falha na abertura: %s\n", strerror(errno));. So you can edit the question and include the message, which might help you get an answer.– Gomiero
Good morning arfneto and Gomiero. I would like to inform you that I discovered the problem ("why of the error"), includes Errno. h indicated by friend Gomiero and understood that the problem was related to directory, soon then I discovered that was using as parameter the 'opening mode' of fopen, a "specifier" that only performs the file opening and not the creation of it (r+), I switched to (w+) and it worked. I know the problem is simple and it was a lack of attention, but as I’m starting I end up making these mistakes sometimes. I apologize and thank you for the valuable information.
– Ramiro Arthur Bayer Martins