Problems formatting arrays and strings in C++
<p>I'm having a simple problem that's been driving me nuts all day. I am trying to open a file on the current user's Desktop without knowing the current user's name.</p>

<p>The idea is that I would use the GetCurrentUser call to the API to get the user name. Then format a string to give the full path directory, and pass that variable into fopen to open the file. Here is the code I'm working on, I get no compiler errors and it compiles fine but nothing writes to the file.</p>

<pre><code>int main() {

  char pathName[200]; // declaring arrays

  char userName[100];

  DWORD userNameSize = sizeof(userName); // storage for user name

  if (!GetUserName(userName, &amp;userNameSize)) { cout &lt;&lt; "user not found"; }

  else { cout "hello" &lt;&lt; userName;} // error checking


  // format for Windows 7 desktop
  sprintf(pathName, "\"C:\\Users\\%s\\Desktop\\text.txt\"", userName); 

  cout &lt;&lt; pathName &lt;&lt; "\n"; // confirms correct location

  const char* fileLocation = pathName; // pointer to full path to pass into fputs

  const char* test = "test";  // test information to write to file to confirm

  FILE *f = fopen(fileLocation,"a+"); // open file in append mode

  fputs(test, f); // write to file

  fclose(f); // flush and exit

  return 0;
}
</code></pre>

<p>Maybe I need to use a different call to format the string? Or declare fileLocation as a different variable type?</p>

<p>I'm fairly new to C++ and would appreciate any tips that would help me to be able to open a file on the current user's Desktop. Thanks.</p>

<p>EDIT IN RESPONSE TO JERRY'S ADVICE:</p>

<p>This is what my latest comment was referring to:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;cstring&gt;
#include &lt;string&gt;
#include &lt;conio.h&gt;
using namespace std;

string location ("C:\\Users\\testuser\\Desktop\\log.dat");

char cstr = char* [location.size()]; //This is a problematic line

strcpy (cstr, location.c_str());

void write(const char* c)
{
    const char* fileLocation = cstr;
    //const char* fileLocation = g_pathName;
    FILE *f = fopen(fileLocation,"a+"); // This is the problematic line right here. 
    if(f!=NULL)
    {
        fputs(c,f); // append to end of file 
        fclose(f);  // save so no entries are lost without being flushed
        }
}


int main ()
{  
  write("test");

  cout &lt;&lt; "done";

  _getch();

  return 0;
}
</code></pre>
