How to create a text file with filename based on user in C++ language?
Mar 24, 2019 at 8:57am UTC
How can I create a program that creates a text file based on user? Thanks for the answers.
Mar 24, 2019 at 9:42am UTC
I doubt that you can do it in a portable manner. You might be able to do it if one of your environment variables contains your username. This worked for me in Windows 7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib> // for getenv
using namespace std;
int main()
{
string extension = ".txt" ;
string user = getenv( "USERNAME" );
string filename = user + extension;
ofstream out( filename );
if ( out )
{
cout << "Created file " << filename << '\n' ;
out << "Hello, " << user << '\n' ;
}
else
{
cout << "boo!\n" ;
}
}
Mar 24, 2019 at 10:34am UTC
At unixoid systems line 10 should be:
string user = getenv( "USER" );
So lastchance's program could be made os independent by:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib> // for getenv
using namespace std;
int main()
{
string extension = ".txt" ;
string user = getenv( "USERNAME" );
if ( user.empty())
user = getenv( "USER" );
string filename = user + extension;
ofstream out( filename );
if ( out )
{
cout << "Created file " << filename << '\n' ;
out << "Hello, " << user << '\n' ;
}
else
{
cout << "boo!\n" ;
}
}
Last edited on Mar 24, 2019 at 10:35am UTC
Topic archived. No new replies allowed.