the following proposed code:
- implements most of the comments to the question
- avoids recursion
- separates the decision to continue adding entries from the actual adding of a new entry.
- cleanly compiles
- documents why each header file is being included
- caveat: most items are properly error checked; however, the calls to
fputs()
should also be error checked
I'll leave it to you to use mkdir
to create any missing directories.
Remember to check if the call to mkdir
was successful, or not where the first time the program is run it may or may not be successful. All following runs of the program should see mkdir
fail.
And now the proposed code:
#include <stdio.h> // perror(), printf(), fprintf(),
// fgets(), fputs(),
// fopen(), fclose()
#include <stdlib.h> // system(), exit(), EXIT_FAILURE
#include <string.h> // strlen(), strchr()
#define MAX_NOME_LEN 30
// prototypes
void inslivros( void );
int main( void )
{
int escolha = 1;
system("cls");
while( escolha )
{
printf("1- Adicionar livro\n"
"0- Voltar para o menu\n-> ");
if( 1 != scanf( "%d", &escolha) )
{
fprintf( stderr, "scanf for escolha failed\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
switch(escolha)
{
case 1:
inslivros();
break;
case 0:
puts( "exiting" );
break;
default: // user entered an invalid menu selection
puts( "invalid menu selection, try again" );
break;
} // end switch()
} // end while()
} // end function: main
void inslivros()
{
char livro[ MAX_NOME_LEN ];
int categoria;
printf( "Qual é o nome do livro que vai inserir?\n-> " );
//gets(livro);
if( ! fgets( livro, sizeof livro, stdin ) )
{
perror( "fgets for line to insert failed" );
exit( EXIT_FAILURE );
}
// implied else, fgets successful
// remove trailing newline
char * newline;
if( (newline = strchr( livro, '\n' ) ) )
{
*newline = '\0';
}
printf( "Qual é a categoria do livro?\n"
"1- Romance\n"
"2- História\n-> " );
if( 1 != scanf("%d", &categoria) )
{
fprintf( stderr, "scanf to input the 'categoria' failed\n" );
exit( EXIT_FAILURE );
}
//implied else, scanf successful
FILE *livros = NULL;
switch( categoria )
{
case 1:
if( ! (livros = fopen("C:\\Livros\\inserelivros.txt", "a") ) )
{
perror( "fopen for inserelivros.txt failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
fputs(livro, livros);
fclose(livros);
FILE *romance;
if( !(romance = fopen("C:\\Livros\\romance.txt", "a")) )
{
perror( "fopen for romance.txt failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
fputs( livro, romance );
fclose( romance );
system("cls");
printf( "Livro inserido com Sucesso!\n" );
break;
case 0:
printf( "Historia not yet implemented\n" );
break;
default:
system("cls");
//printf("Nome inválido!\n");
printf( "invalid menu selection\n" );
break;
} // end switch()
} // end function: inslivros