Hi,im new to c++, i use Dev-C++ to compile my programs
i have little problem with ofstream function,i think you guys can help me
What program does?
Lets say my Computer name is nixon-pc.
Program displays text in cmd: "File nixon-pc.html has been created"
and than create file C:\nixon-pc.html .

Fist part works well,but i cant deal with ofstream function when it should create file C:\nixon-pc.html

Here is the source

#include <windows.h>
#include <iostream>
#include <fstream>

using  namespace std;


void GetHostname() {
      
  char  ComputerName [MAX_COMPUTERNAME_LENGTH + 1];
  DWORD cbComputerName = sizeof ( ComputerName );
  GetComputerName ( ComputerName, &cbComputerName );  
   
  cout << "File " << ComputerName << ".html has been created" << endl;
  system("pause");
}

void CreateFile() {
        
     ofstream out("c:\\file.html");
     out << "This is a short text.";
     out.close();
}

int main() {

          GetHostname();
          CreateFile();    
          return 0;
}

So... everythig works fine except this ofstream out("c:\\file.html"); I need to apply variable ComputerName to this line, exam. ofstream out("c:\\",ComputerName,".html"; Something like that

Hope you guys understand me,thx for help! :)

Member Avatar for iamthwee

I would probably use .c_str() to convert the std::string as it may be necessary.

guys i have no idea how to use this functions,im noob
can u write me a single line of code,it wil l help me a lot!
i dont think its hard to solve this

guys i have no idea how to use this functions,im noob
can u write me a single line of code,it wil l help me a lot!
i dont think its hard to solve this

The goal is to create a string and end up with the full filename, with the path and extension, so you have "c:\", computerName, and ".html", and you want to concatenate them into:

"c:\computerName.html"


Do this:

string computerName = "MyComputer";
string compnamewithfullpath = "c:\\" + computerName + ".html";
ofstream out(compnamewithfullpath.c_str());

Note the \\ rather than \ since the first backslash acts as the escape character. Looks like you already realize that, but i figured I'd point it out.
Make sure to add this to the top:

#include <string>

You should still look up the links/ideas that iamthwee and mitrmkar gave you. .= is the concatenation operator. It wasn't needed here since I did it all in one line, but it would have been needed if it was done in two lines. c_str() was needed because the ofstream constructor takes a const char* argument, not a string argument. c_str () converts a string to const char* .

http://www.cplusplus.com/reference/iostream/ofstream/ofstream.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.