问题描述
#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();
}
这应该打开一个文本文件并将其内容打印到控制台。 但这是行不通的。错误消息总是被触发,并且不打印文件!
我还想知道如何用相对的文件路径替换完整的文件路径,使其在其他计算机上工作,或者是否移动了项目。
解决方法
如果您输出路径
const char* path = "C:\Dev\devAstroides\printFileToScreen\Hello.txt";
std::cout << path;
您会发现输出实际上是
C:DevdevAstroidesprintFileToScreenHello.txt
正如@MikeCAT指出的那样,您需要通过将斜杠加倍来加倍转义。像这样
const char* path = "C:\\Dev\\devAstroides\\printFileToScreen\\Hello.txt";
见下文:
https://en.cppreference.com/w/cpp/language/escape
关于相对路径,如果您的文件夹将可执行文件放在同一位置,那么您可以像正常一样使用相对路径。例如,如果在与应用程序相同的文件夹中有一个文本文件,则只需将路径设置为
const char* path = "Hello.txt";