0
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

int main()
{
    const char* path = "C:\Dev\devAstroides\printFileToScreen\Hello.txt";
    std::string Code;
    std::ifstream File;
    File.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    try
    {
        // open files
        File.open(path);
        std::stringstream Stream;
        // read file's buffer contents into streams
        Stream << File.rdbuf();
        // close file handlers
        File.close();
        // convert stream into string
        Code = Stream.str();
    }
    catch (std::ifstream::failure & e)
    {
        std::cout << "ERROR::FILE_NOT_SUCCESFULLY_READ" << std::endl;
    }

    std::cout << Code.c_str();
}

This is supposed to open a text file and print its content to the console. But it doesn't work. The error message is always triggered and it doesn't print the file!

I also wonder how one can replace the full file-path with a relative one, so it works on other computers, or if the project is moved.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Q broms
  • 1
  • 1
  • 2

1 Answers1

0

If you output your path

const char* path = "C:\Dev\devAstroides\printFileToScreen\Hello.txt";
std::cout << path;

you'll find the output is actually

C:DevdevAstroidesprintFileToScreenHello.txt 

As @MikeCAT pointed out you need to double escape your slashes by doubling them up. Like so

const char* path = "C:\\Dev\\devAstroides\\printFileToScreen\\Hello.txt";

See below:

https://en.cppreference.com/w/cpp/language/escape

With regards to a relative path, if your folders will sit with the executable in the same place then you can just use a relative path like normal. For example if there is a text file in the same folder as the application you can just set the path to

const char* path = "Hello.txt";
Tom James
  • 26
  • 3
  • In C++11 and later, you can alternatively use a [raw string literal](https://en.cppreference.com/w/cpp/language/string_literal) instead, then you don't need to ecape the ```\``` characters: `const char* path = R"(C:\Dev\devAstroides\printFileToScreen\Hello.txt)";` – Remy Lebeau Oct 28 '20 at 17:17
  • As for using relative paths, you are assuming the process's *working directory* is the same as the folder containing the EXE, but that is not a guarantee. You really should avoid using relative paths altogether, always use absolute paths. If you need to access paths relative to the EXE's location, then retrieve the EXE's actual location at runtime (from `main()`'s `argv[0]` parameter, or platform APIs like `GetModuleFileName()`, etc) and then manipulate that value to create full paths as needed. – Remy Lebeau Oct 28 '20 at 17:21