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
Okay, nice code. What’s your question?
– Victor Stafusa
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
– Dennis Paiva
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.
– anonimo