Home > Software engineering >  How do I open a file txt in a specific folder using visual studio c ?
How do I open a file txt in a specific folder using visual studio c ?

Time:11-30

This is the part of code where I try to open the file f1.txt, it is complete path is C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt

ifstream fichier("C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt", ios::in);

The file cannot be opened and I don't know why?!

NSGA2-CDS is the folder that contain the visual studio solution

CodePudding user response:

You have to escape backslashes in the path string:

ifstream fichier("C:\\Users\\Hp\\Desktop\\NSGA2-CDS\\DataSet\\f1.txt", ios::in);

This has nothing to do with file I/O as such; it's a feature of string literals: \ is used to escape special characters (such as \n, \t), so when it appears in a string, it needs to be escaped as well.

CodePudding user response:

you can also use raw string literal so you don't need to escape individual char.

ifstream fichier(R"(C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt)", ios::in);
  • Related