【问题标题】:Error when changing location of ofstream file C++更改流文件 C++ 的位置时出错
【发布时间】:2013-04-29 16:10:21
【问题描述】:

我的代码如下所示:

std::vector <std::string> info;
info.push_back("10");
info.push_back("this is a line to print");
std::ofstream myfile;
myfile.open("list.txt");
myfile<<"first*"<<info[0]<<"\n";

效果很好,但是当它创建文件并打印信息时,但是当我将其更改为:

std::vector <std::string> info;
info.push_back("10");
info.push_back("this is a line to print");
std::ofstream myfile;
myfile.open("Output\\list.txt");
myfile<<"first*"<<info[0]<<"\n";

它会创建文件,但是当我尝试将文件输出到文件时,整个事情就崩溃了。我在 Windows 8 上使用带有 GNU gcc 编译器的 code::blocks。

【问题讨论】:

  • 什么是“输出”?好像您正在使用它作为相对路径。但实际上不是。
  • 它是一个文件夹,我已将其包含在程序运行所在的文件夹中
  • pushback 应该是 push_back。 "\n 应该是 "\n"。我创建了一个文件夹 Output 并将您的代码复制到与 Output 目录相同级别的文件中,运行它,它工作正常。我可以在文件中看到 first*10输出文件夹下的list.txt
  • 对,抱歉,这些都是我打错了,代码中没错,但我会继续解决这个问题
  • 我怀疑,如果没有绝对提供路径,程序只会将文件存储在默认文件夹中。因此,如果您希望将文件写入您自己选择的文件夹中,请尝试提供绝对路径。例如:C:\doc\projects\abc\Output。

标签: c++ windows ofstream


【解决方案1】:

将绝对路径提供为“C:\Documents\yourprojects\yourcurrentproject\Output\list.txt”。它会正常工作。我尝试过这个。

【讨论】:

  • 使用单反斜杠 `` 可能会导致目录名称出现问题。首选“/”(正斜杠)。
猜你喜欢
  • 1970-01-01
  • 2019-12-04
  • 2022-01-07
  • 1970-01-01
  • 2020-05-18
  • 2023-04-07
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多