fopen returning NULL

Asked

Viewed 37 times

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?

  • 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 to printf("Falha na abertura: %s\n", strerror(errno));. So you can edit the question and include the message, which might help you get an answer.

  • 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.

1 answer

0

@Ramiro I believe that the eerro in your code is by syntax error , because it was missing the character & in scanf’s , and so the compiler finishes the execution of the program , and another thing is that if you use the "w+' or "w"the file will be created every time you compile the code, yes , but , that same file that was created , then it will be created again and also reset deleting all the data that has already been written in it , that so will be lost , then better use the type "a"of append , which opens the file for reading and can also record data from the end of it , keeping its content , and then its code with some modifications could be like this :

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define cls system("cls");
#define getch() _getch()
int rcaracter();
int rpalavra ();
int main( void )
{
    int i,opt;
    char palavra[30];
    do
    {
        printf("\n\t  Programa : Arquivo    \n\
                \r\t    --- Menu ---        \n\
                \r\t[ 1 ] - Arquivo Caracter\n\
                \r\t[ 2 ] - Arquivo Palavra \n\
                \r\t[ 3 ] - Sair            \n\
                \r\t        Opção : "        );
        scanf("%d", &opt);
        cls
        switch ( opt )
        {
        case 1:
            rcaracter();
            break;
        case 2:
            rpalavra();
            break;
        case 3:
            break;
        default:
            printf("opcao invaLida !\n");;;;;
        }
    }while( opt != 3 );
    return 0;
}
int rcaracter()
{
    char caracter;
    FILE* arq;                                /// FILE é um ponteiro qq e mais seguro aqui dentro da fun
    /// arq = fopen("arquivo.txt", "r+");     /// r de read   lêlê e Gravaa no iniciô do Arquivu !
    arq = fopen("arquivo.txt", "a");          /// a de Append lêlê e Gravaa no FinAu  do Arquivu !
                                              /// tenta abrir o arquivo
    if(arq == NULL)                           /// se o arquivo nao existir
    {
        printf("Falha na abertura\n");        /// escreve msg de erro inf o usuario disso
        printf("esse Arquivo ainda nao existe , e serah criado AgoRa ! . . .\n   Tecle\n");
        arq = fopen("arquivo.txt","w");       /// cria abre e reseta  o arquivo para gravar
                                              /// no inicio dele
        getch();                              /// espera ethernamente até clicar em algum botao
        cls                                   /// Macro
    }
    else
    {
        printf("Digite o caracter -: ");
        fflush(stdin);
        setbuf(stdin,NULL);                    /// limpar o buffer antes de scanf
                                               /// scanf tem problemas em ler cractere
        scanf("%c", & caracter);               /// Faltou o & de endereço da variavel
                                               /// ele finaliza a execução
        cls                                    /// MAcro
        while ( caracter != 'f' )              /// enQuanto nao digitar   f
        {
            fputc(caracter, arq);              /// gravar um caractere no arquivo txt
            if ( ferror ( arq ) )              /// se houver erro na gravação
            {
                printf("Falha na gravação\n"); /// mostra msg
                getch();                       /// espera até ehernamente até pressionar alguma tecla
                cls                            /// uma MaCro para LimparAtela
            }
            else
            {
                printf("Sucesso . . . !\n    ");/// escreve msg para o usuario
            }
            printf("Digite outro caracter ou   'f'   para sair --: ");
            fflush(stdin);
            setbuf(stdin,NULL);
            scanf("%c", & caracter);            /// faltou o & , termina a execução sem passar por fclose
                                                /// que faz efetivamente a validação de gracacao
        }
    }
    fclose( arq );                              /// validar a gravacao dos dados no arquivo
    return 0;                                   /// retorna para o windows uma msg q pode ser usada
                                                /// em outro programa
}
int rpalavra()
{
    printf("estah no rpalavra . . . !\n");
    getch();
}

Browser other questions tagged

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