Maloser
Maloser

Reputation: 35

c++ Write Chars into Batch file

Why does this give error at '%' as incorrect formatted speical character.

ofstream batch;
batch.open("C:\tesfile.bat", ios::out);
batch << "@echo off\n";
batch << "set Dir=C:\Users\%USERNAME%\AppData\ \n";

Also i gave c:\ to create bat file it creates bat file at the app folder (where the app is placed).

Please help.

Upvotes: 2

Views: 123

Answers (2)

SergeyA
SergeyA

Reputation: 62583

You should either escape special character \ in your string, or use C++11 raw literals (much better option in my view!) like this:

batch.open(R"(C:\tesfile.bat)", ios::out);

Upvotes: 2

Gillespie
Gillespie

Reputation: 6561

In a string, you need to escape your backslashes (\) as \\. Otherwise, the compiler thinks you are trying to insert special characters like \n:

batch.open("C:\\tesfile.bat", ios::out);
batch << "@echo off\n";
batch << "set Dir=C:\\Users\\%USERNAME%\\AppData\\ \n";

As a thought exercise, imagine what would happen if you didn't escape your backslashes:

batch.open("C:\nifty_folder", ios::out); //\n in "nifty" causes a newline!

In fact, your original code has an unintended consequence!

batch.open("C:\tesfile.bat", ios::out); //\t is a tab!

Upvotes: 1

Related Questions