1

I just started new project in Visual Studio 2017 and I tried to write some text into file. But after I run my code, no file is created.

int main()
{
    ofstream file_program("D:\test2.txt", ios::out);
    if (file_program.is_open())
    {
        file_program << "test";
        cout << "OK";

        file_program.close();
    }

    int age;
    cin >> age;

    return 0;
}

What am i doing wrong?

Sk1X1
  • 1,305
  • 5
  • 22
  • 50
  • 6
    Try `"D:\\test2.txt"` instead of `"D:\test2.txt"` - `\t` in a string has special meaning, so you need to escape the first \ – UnholySheep Dec 06 '17 at 12:55
  • 1
    You can also use forward slash `/`. Works fine on both Windows and Linux. – Bo Persson Dec 06 '17 at 12:57
  • related https://stackoverflow.com/questions/10220401/rules-for-c-string-literals-escape-character – UKMonkey Dec 06 '17 at 13:01
  • So stupid :/ i was trying relative and absolute path, different folders because windows rights, but this didn't cross my mind... Thank you guys! – Sk1X1 Dec 06 '17 at 13:06
  • 1
    Next time, use a debugger and step into functions; you'd see that the argument wasn't showing what you thought it would be showing; and now you likely have some very strangely named files kicking around ... if the open succeeded. – UKMonkey Dec 06 '17 at 13:08

1 Answers1

0

In C++ you have to escape the backslash.

"D:\test2.txt"

Here you have '\t' which is effectively a tabulator.

"D:\\test2.txt"

Would be correct.

Blacktempel
  • 3,935
  • 3
  • 29
  • 53