【问题标题】:Trying to open and read files with fstream and sstream尝试使用 fstream 和 sstream 打开和读取文件
【发布时间】: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


【解决方案1】:

如果你输出你的路径

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";

【讨论】:

  • 在 C++11 及更高版本中,您可以替代地使用 raw string literal,然后您不需要转义 \ 字符:const char* path = R"(C:\Dev\devAstroides\printFileToScreen\Hello.txt)";
  • 至于使用相对路径,您假设进程的工作目录与包含EXE的文件夹相同,但这并不能保证。您确实应该完全避免使用相对路径,始终使用绝对路径。如果您需要访问相对于 EXE 位置的路径,则在运行时检索 EXE 的实际位置(来自main()argv[0] 参数,或GetModuleFileName() 等平台API),然后操纵该值以创建完整的根据需要提供路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 2015-04-19
  • 2011-05-05
  • 2012-10-17
相关资源
最近更新 更多