【发布时间】:2021-02-10 23:24:59
【问题描述】:
#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();
}
这应该打开一个文本文件并将其内容打印到控制台。 但它不起作用。错误信息总是被触发,并且不打印文件!
我还想知道如何将完整的文件路径替换为相对路径,以便在其他计算机上运行,或者如果项目被移动。
【问题讨论】:
-
\用于 C++ 中的转义序列。您应该使用\\在字符串中表示\。 -
在 Windows 中也允许使用 / 作为路径分隔符,除非您使用的是 unc 路径。你也逃不掉。
-
我希望你的编译器会警告你无效的转义序列。
标签: c++ string runtime-error fstream file-handling