Error when user provides file name

Asked

Viewed 69 times

0

#include <stdio.h>

int main(void)
{
    char ch;
    int caracteres = 0;
    int linhas = 0;
    int imprimiveis = 0;


    FILE *arquivo;
    char nome[50];

    printf("Escreva o nome do arquivo: ");
    fgets(nome, 50, arquivo);

    arquivo = fopen(nome,"r");
    if (arquivo == NULL)
    {   
        printf("Erro, arquivo nao existe.");
    }
    else
    {
        while((ch = fgetc(arquivo))!= EOF)
        {
            caracteres++;
            if (ch != '\n')
            {
                imprimiveis++;
            }
            else if(ch == '\n')
            {
                linhas++;
            }
        }
    }

    fclose(arquivo);

    printf("Numero de caracteres lidos: %d\n",caracteres);
    printf("número de caracteres imprimíveis lidos: %d\n",imprimiveis);
    printf("número de linhas: %d\n",linhas);
}

I want to know how to make the user choose the file name. I tried to do so but is giving segmentation failure. What’s wrong?

  • 1

    Okay, nice code. What’s your question?

  • I want to know how to make the user choose the name of the file.I tried to do so but is giving segmentation failure

  • Note that the fgets function puts the end-of-line character ( n) in the read string whenever it does not reach the character limit, so you should replace the last n with 0.

2 answers

1

The error is here:

    fgets(nome, 50, arquivo);

At this point, arquivo is not a pointer with a valid content. What you wanted is this:

    fgets(nome, 50, stdin);
  • true, I had this one. But, it keeps making the same mistake. Now that I can’t really say why.I thank you for the other comment.

  • fgets() does not remove the \n end of line read. fopen() will fail if the file name displays \n in the end!

1

You can use the function isprint() of the standard library ctype.h to test whether a character is printable.

The function fgets() does not remove the \n of the end of string read, and fopen() will fail if the file name has \n at the end. How about using scanf() in place of fgets() to avoid this complication ?

Look at your rewritten code:

#include <stdio.h>
#include <ctype.h>
#include <limits.h>

int main( void )
{
    int i = 0;
    int caracteres = 0;
    int linhas = 0;
    int imprimiveis = 0;
    FILE *arquivo = NULL;
    char nome[ PATH_MAX + 1 ];
    char linha[ PATH_MAX + 1 ];

    printf("Escreva o nome do arquivo: ");
    scanf( "%s", nome );

    arquivo = fopen( nome,"r" );

    if( arquivo == NULL )
    {
        printf("Erro, arquivo '%s' nao existe.\n", nome );
        return 1;
    }

    while( fgets( linha, PATH_MAX, arquivo ) )
    {
        i = 0;

        while( linha[i] )
        {
            if( isprint(linha[i]) )
                imprimiveis++;

            i++;
        }

        caracteres += i;
        linhas++;
    }

    fclose(arquivo);

    printf("Caracteres lidos: %d\n", caracteres );
    printf("Caracteres imprimiveis lidos: %d\n", imprimiveis );
    printf("Numero de linhas lidas: %d\n", linhas );

    return 0;
}

Test file (entrada.txt):

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
praesentium voluptatum deleniti atque corrupti quos dolores et quas
molestias excepturi sint occaecati cupiditate non provident, similique
sunt in culpa qui officia deserunt mollitia animi, id est laborum et
dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil
impedit quo minus id quod maxime placeat facere possimus, omnis voluptas
assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et
aut officiis debitis aut rerum necessitatibus saepe eveniet ut et
voluptates repudiandae sint et molestiae non recusandae. Itaque earum
rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus
maiores alias consequatur aut perferendis doloribus asperiores repellat.

Exit:

Escreva o nome do arquivo: entrada.txt
Caracteres lidos: 844
Caracteres imprimiveis lidos: 833
Numero de linhas lidas: 12
  • our! Brigadeo man, helped too!!!!

Browser other questions tagged

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