Abhijit Abhijit - 1 year ago 69
C++ Question

is_open() function in C++ always return 0 value and getLine(myFile, line) does not return anything

Trying to read a file in C++ using fstream.
But the is_open() function always return 0 result and readline() does not read anything. Please see the code snippet below.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
string line;
ifstream myfile("D:\xx\xx\xx\xx\testdata\task1.in.1");
if (myfile.is_open()) {
while (getline(myfile, line)) {
cout << line << '\n';

cout << "Unable to open file";

return 0;

Answer Source

you think you're opening D:\<somepath>\testdata\task1.in.1

but in fact you're trying to open D:\<somepath><tabulation char>estdata<tabulation char>ask1.in.1 since \t is interpreted as a tabulation.

(like \n is a newline in printf("hello world\n");)

(\x is special too BTW that's not the real path or you would have had another error: error: \x used with no following hex digits which maybe would have talked to you better!)

You have to escape the backslashes like this:


Windows also accepts paths like those, more convenient, unless you want to generate batch scripts with cd commands or the like that would require backslashes (/ is used as option switch in batch commands):


Last word: dirty way of getting away with it:


Using uppercase in that case would work

  1. because windows is case insensitive
  2. C would let the backslashes as is.

But that's mere luck. A lot of people do that without realizing they're very close to a bug. BTW a lot of people capitalize windows paths (as seen a lot in this site) because they noticed that their paths wouldn't work with lowercase without knowing why.