Problem with manipulation of txt files in C ++

3

I'm developing a C ++ program that should read the keyboard data by storing them with hash , after reading it it should have the save option in its main menu.

I can read the save files using hash and everything.

The problem is when creating the file, I would like to make a for you to create the files with the default name, example

data_1
data_2
data_3
assim por diante

I made this code, but for some reason it creates only the zero index file and as if repeating the name and replacing the file 4 times that is the size of the defines TAM ;

void func_arquivo::cria_arquivo(){
   ofstream arquivo;
    for(int i=0;i<TAM;i++){
        char nome[TAM];
        sprintf(nome, "Data-%d.txt",i);
        arquivo.open(nome, ios::app);
        arquivo.close();
    }
}
    
asked by anonymous 27.10.2016 / 13:25

1 answer

2

According to the sprintf function documentation:

  

The size of the buffer should be large enough to contain the entire   resulting string (see snprintf for a safer version).

Second your comment buffer size is 4 , you are trying to save at least 10 characters ...

You can increase buffer capacity, for example char nome[FILENAME_MAX] or use the snprintf function, where the maximum number of bytes which will be written as follows:

char nome[FILENAME_MAX];
// ...
snprintf(nome, FILENAME_MAX, "Data_%d.txt", i);
// ....

See DEMO

    
27.10.2016 / 15:23