file name (c ++)

1

I have a question:

How can I make or modify this subprogram so that when I enter the name of the file as input parameter, give me this name.txt?

I attach the Subprogram here:

void guardar_fic(string nom_fic){
   ofstream entrada;
   entrada.open("nom_fic.txt");
   entrada<<"EOO"<<endl;
   entrada.close();
}

Pd: In the case of putting for example; guardar_fic(PEPE) create me the file as PEPE.txt

Thank you.

    
asked by martinezzz69 13.04.2017 в 17:19
source

2 answers

2

What I think you could do is

nom_fic += ".txt";
ofstream entrada;
entrada.open(nom_fic.c_str());
entrada<<"EOO"<<endl;
entrada.close();

Try it to see if it works for you.

    
answered by 13.04.2017 в 19:13
1

See the constructors of std::ofstream :

basic_ofstream()

Create a data stream from write to file that does not point to any file.

explicit basic_ofstream(const char*, std::ios_base::openmode = ios_base::out)

Creates a write-to-file data flow that points to the file whose name is stored in the array of characters received as the first parameter.

explicit basic_ofstream(const std::filesystem::path::value_type*, std::ios_base::openmode = ios_base::out)

Create a data stream from write to file that points to the file that is in the route received as the first parameter.

explicit basic_ofstream( const std::string&, std::ios_base::openmode = ios_base::out)

Creates a data stream from write to file that points to the file whose name is stored in the string received as the first parameter.

explicit basic_ofstream( const std::filesystem::path&, std::ios_base::openmode = ios_base::out)

Create a data stream from write to file that points to the file that is in the route received as the first parameter.

So you can open a file with std::string , so your function would look like this:

void guardar_fic(std::string nom_fic){
   if (std::ofstream entrada{nom_fic + ".txt"}) {
       entrada << "EOO\n";
   }
   // No es necesario llamar a entrada.close,
   // se llama automáticamente al salir del if.
}
    
answered by 11.04.2018 в 13:05