Problem with handling txt files in C++

Asked

Viewed 102 times

3

I am developing a C++ program that should read the keyboard data store them with hash, after performing the reading it must have in its main menu the save option.

I can read the save files using the hash and all.

The problem is at the time of creating the file, I would like to do a for that 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 file of zero index and as if I kept 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();
    }
}
  • 1

    what size of the variable TAM even?

  • the size of the TAM define is 4!

1 answer

2


According to the function documentation sprintf:

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

According to your comment the size of buffer is 4, you’re trying to save at least 10 characters...

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

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

See DEMO

  • Perfect worked , only to understand then the problem was the size of the char on which I was writing the name, how was it too small could only hold the first of the loop? right?

  • @Eduardo That’s right...

  • I asked him about the TAM to give that answer, only you were faster kkkkk

  • But actually @Eduardo, I don’t even know how it ran the first time. What happened was that you set a string size of value 4, that is, you could only add 4 characters in the variable, which was not happening because you added at least 10.

  • Yes @Christianfelipe, really I traveled cool!!

Browser other questions tagged

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