Dynamic filename usage for file creation

Asked

Viewed 27 times

-1

I want to create files with dynamic names for storing logs, however, I have no idea how to get the name I want and also do not know how to format the string and use it with the "path/filename.txt".

My current code for file writing:

//Inserir no arquivo de log
void appendKeyLog(Text key){
    ofstream logfile;
    logfile.open("sgdev_log.txt", ios::app);
    logfile << key;
    logfile.close();

The name of the file I want to use is the hostname (which I don’t know how to acquire) the user is in (I believe is the best name for an identifier in my project), such a name would replace the current "sgdev_log.txt". And finally, I don’t know how I would do to assemble and use the string with caminho_específico + nome_do_arquivo.

  • This can help: https://stackoverflow.com/questions/13509532/how-to-find-and-replace-text-in-a-file-with-c-sharp

  • This one is to replace inside the file

  • I know. You either saved where your file is or?

  • i want to save the file name dynamically, regardless of the location chosen, not the content.

  • You want the user to add the place?

  • no, I need to collect the machine name (hostname) and use it to create the file with the same host name

  • I figured it out, I’ll post the answer

Show 2 more comments

1 answer

0


After verifying that there is a method to collect the hostname (getenv("COMPUTERNAME"), this to windows), performed some tests concatenating the return of getenv with the file extension and worked, follows below the code for creating file with dynamic name.

#include <string>

void appendKeyLog(Text key, string hostName){
    ofstream logfile;
    logfile.open((hostName + ".txt"), ios::app);
    logfile << key;
    logfile.close();
}

Browser other questions tagged

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