I want to store files by naming them from file 1.dat.
Everything is fine but when I restart the program, it stores file naming from file 1.dat again but I wants to store it from next numbers
For example if previous file was named 3 then it will store from 4 not from 1
again as the data will lose from previous file as it will overwrite that file.
I have tried a lot of methods. Tried several hours figuring it out by applying bool and loops and if statements but failed.
Scan the directory of interest to determine the names of files which are already present.
We can use the standard filesystem library to do this. https://en.cppreference.com/w/cpp/filesystem
#include <iostream>
#include <fstream>
#include <string>
#include <filesystem>
#include <regex>
namespace fs = std::filesystem ;
// return the largest file number nnn of the files named 'file nnn.dat' in the directory
int get_last_file_number( const fs::path dir = fs::current_path() )
{
int last_file_num = 0 ;
// for each entry in the directory
for( constauto& entry : fs::directory_iterator(dir) )
{
// get the file name component of the path
const std::string file_name = entry.path().filename().string() ;
staticconst std::regex file_name_re( "file (\\d+)\\.dat" ) ;
std::smatch match ;
// if the file name is of the expected form 'file nnn.dat'
if( std::regex_match( file_name, match, file_name_re ) )
{
// extract the number as an integer
constint file_num = std::stoi( match[1] ) ;
// update last_file_num if it is a larger integer
if( file_num > last_file_num ) last_file_num = file_num ;
}
}
return last_file_num ;
}int next_file_number( const fs::path dir = fs::current_path() )
{
return get_last_file_number(dir) + 1 ;
}
int main()
{
std::cout << "how many files? " ;
int n ;
std::cin >> n ;
// the next file number starts at fn
constint fn = next_file_number() ;
for( int i = 0 ; i < n ; ++i )
{
// the file number of this file is fn+i
const std::string fname = "file " + std::to_string(fn+i) + ".dat" ;
std::cout << "creating file '" << fname << "'\n" ;
std::ofstream(fname) << i << " (" << fn+i << "). this is just an example\n" ;
}
}