當我運行下面的代碼,foobar_fname
得到由foobar_fname
內容覆蓋時getline
運行:爲什麼std :: getline覆蓋包含文件名的char數組?
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
包含「簡單的文本內容」,輸出的樣子:
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等不是可行的解決方案)。
可否請你會這麼好心,並提供了[MCVE]使用,這裏的[對於初學者東西(http://coliru.stacked-crooked.com/a/d4727423864d880e)。 (或至少嘗試ideone,提供標準輸入更容易) –