Automated file help

Hello, I need help writing code for automated incremental file names.
This is what I have right now.

1
2
3
4
5
6
7
8
9
10
11
FILE *output;
char output_file_name[ NAME ];

printf( "\nEnter an output file name: " );
scanf( "%s", output_file_name );

bool print_header = 0;//Flag to print file header

output = fopen( output_file_name, "w" );
      
fclose(output);
Last edited on
Do you want to use C or C++? Right now you seem to be avoiding C++ at all costs.
C++ is fine. I was going by an old formatted code.
Here's what I would start with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::size_t num = 0;
    std::string name;
    do
    {
        name = "log_" + std::to_string(num) + ".txt";
        ++num;
    }while(std::ifstream{name} || !std::ofstream{name});
    std::cout << "Log file for this session is " << name << std::endl;
    {
        std::ofstream of {name};
        of << "This is log #" << num << "." << std::endl;
    }
    std::cout << "End of session, log file closed." << std::endl;
}
It's not very efficient and has a very unlikely possible bug, but it's something to start with.
Last edited on
Topic archived. No new replies allowed.