-3

I am writing the function to insert the book. The function is inslivros();. Here is the code:

int inslivros()
{
    char livro[30];
    int categoria;
    printf("Qual é o nome do livro que vai inserir?\n-> ");
    gets(livro);
    printf("Qual é a categoria do livro?\n1- Romance\n2- História\n-> ");
    scanf("%d", &categoria);
    if(categoria == 1)
    {
        FILE *livros;

        livros = fopen("C:\Livros\inserelivros.txt", "w+");
        fputs(livro, livros);
        fclose(livros);

        FILE *romance;

        romance = fopen("C:\Livros\romance.txt", "w+");
        fputs(livro, romance);
        fclose(romance);

        system("cls");
        printf("Livro inserido com Sucesso!\n");
    }
    else
    {
        int escolha;
        system("cls");
        printf("Nome inválido!\n");
        printf("1- Adicionar livro\n0- Voltar para o menu\n-> ");
        scanf(escolha);
        switch(escolha)
        {
        case 1:
            system("cls");
            inslivros();
        case 2:
            system("cls");
            main();
        }
    }

}

When categoria == 1, the folder and file are not being created. Where did I go wrong?

Jay333
  • 103
  • 10
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/161535/discussion-on-question-by-rodrigo-silva-c-file-creation-not-working). – Andy Dec 19 '17 at 14:25
  • If you need to create a directory path, you can consider [How can I create a directory trein in C++/Linux?](https://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux/675193#675193) The answer is both C and C++ code; it uses the `mkdir()` system call and should work OK on WIndows except for path separators (it should not be hard to treat backslashes as alternatives to slashes; Windows already handles slashes but conventionally uses backslashes). – Jonathan Leffler Dec 19 '17 at 16:31

2 Answers2

2

When categoria == 1, the folder and file are not being created. Where did I go wrong?

fopen doesn't create folders/directories for you - it only create files. So if C:\Livros doesn't exist when running the program, the program will fail.

To create the folder/directory look at mkdir

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

the following proposed code:

  1. implements most of the comments to the question
  2. avoids recursion
  3. separates the decision to continue adding entries from the actual adding of a new entry.
  4. cleanly compiles
  5. documents why each header file is being included
  6. 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
user3629249
  • 16,402
  • 1
  • 16
  • 17