c++ - 为什么 std::getline 会覆盖包含文件名的 char 数组?

标签 c++ linux

当我运行以下代码时,当 getline 运行时,foobar_fname 会被 foobar_fname 的内容覆盖:

ostringstream st_foobar_fname;
st_foobar_fname << foostr << BAR_CONST << barstr;
const char *foobar_fname = (st_foobar_fname.str()).c_str();

ifstream foobar_file(foobar_fname);
debug("Reading '%s'", foobar_fname);

string foobar_def = "";
if (getline(foobar_file, foobar_def)) {
  debug("'%s' reported message '%s'", foobar_fname, foobar_def.c_str());
} else {
  error("Unable to read '%s'", foobar_fname);
}

例如,如果 foobar_fname=/home/user/fname/home/user/fname 包含“simple-text-content”,则输出如下所示:

Reading '/home/user/fname'
'simple-text-content' reported message 'simple-text-content'

但是,如果 /home/user/fname 不存在(且 getline 失败),则输出正确:

Reading '/home/user/fname'
Unable to read '/home/user/fname'

我哪里出错了?

(这是一段旧代码,我不想为其引入新的依赖项,因此 c++11、boost 等不是可行的解决方案)。

最佳答案

您正在看到未定义行为的症状。

st_foobar_fname.str()

返回一个std::string

const char *foobar_fname = (st_foobar_fname.str()).c_str();

存储一个指针,该指针在该行完成执行后无效,因为它对应于一个临时对象。临时对象被销毁,您只剩下一个悬空指针。

如果您想保留该值,请使用 std::string

std::string foobar_fname = st_foobar_fname.str();

关于c++ - 为什么 std::getline 会覆盖包含文件名的 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38212643/

相关文章:

C++ 多项式加法

c - 扩展一个 IPv6 地址,以便我可以将它打印到标准输出

php - Jenkins 用户无法运行 composer install

c++ - 通过 typedefs 消除歧义是 C++ 中的非标准行为吗?

c++ - 在模板中使用静态变量

c++ - 为什么我不能用 "\x"初始化字符串

c++ - 使用宏访问 C 中的结构成员名称

linux - 如何设置仅对一个域/子域有效的 mod_security 规则?

c - 从 Linux 内核运行外部二进制文件

linux - avahi-daemon 不启动(无法创建运行时目录)