0

I am trying to create a program to open a file using values in environment variables..

My code:

#include<iostream>
#include<cstdlib>
#include<sstream>
#include<cstring>
using namespace std;
void main(int argc, char *argv[])
{
std::stringstream stream;
int a;
cout<<"Press 1 to open Remainder: "<<endl;
cout<<"Press any other key to exit: "<<endl;
cin>>a;
if(a==1)
{
    system("\"C:\\Documents and Settings\\%USERNAME%\\My Documents\\CorelDRAW X3.txt\"");
//  system(stream.str().c_str());
}
else
{
    exit(0);
}
}

This is the output:

Press 1 to open Remainder:
Press any other key to exit:
1
'C:\Documents' is not recognized as an internal or external command,
operable program or batch file.
Press any key to continue . . .

But when i type my username then it runs perfectly..

I want to use this program in another computer so i used environment variables

Any help?

Thanks.

  • It would be easier to do this with a batch file. As already noted in some answers, one way to fix things is to quote the path. Another way is to use short names. One way to find the short path to the current directory in the command interpreter, is `for /d %d in (.) do @echo %~fsd`. – Cheers and hth. - Alf Jul 20 '14 at 14:36

3 Answers3

0

You need an extra set of quotes. Use it like this.

system("\"\"C:\\Documents and Settings\\%USERNAME%\\My Documents\\CorelDRAW X3.txt\"\"");
Dodu
  • 224
  • 1
  • 6
0

Your problem is the (mis)use of the system function call to open the text file. It doesn't cope with spaces in the filename as those are used by system to separate the program from its parameters. Whilst this can be solved by putting the program (or in your case the text file) name in an additional set of quotes, this isn't really the right fix.

Try using ShellExecute instead from the Windows API - there's a good example in this answer.

Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

You should avoid using system (), but if you want to, you can get the username with GetUserName function, and put this into the string.

schacker22
  • 439
  • 2
  • 5
  • 12