gpt4 book ai didi

c++ - 无法在 Linux 中使用 c_str() 打开文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:56 25 4
gpt4 key购买 nike

在 Windows 上,我可以毫无问题地从字符串打开文件。在 Linux 上(它需要工作的地方)我无法打开文件。

    string name;

//open 1st file, with the next file name - this works
fstream file( "data.dat", ios::in);

if(file.good()){
getline(file, name);

//some code here

file.close();
}else{
return 1;
}


// this here does not work
fstream file1(name.c_str() , ios::in);
if(file1.good()){

//some code here

file1.close();
}else{
cout<<"can't open file"<<endl;
return 1;
}

如果不是 name.c_str() 我直接写文件名它就可以工作,但是每次尝试从文件中获取名称都以文件无法打开而告终。

我试过从 name 创建 const char*,也没用。

最佳答案

文件可能有 Windows-style line endings .清理文件,或检查并删除每行末尾的任何回车符 \r

关于c++ - 无法在 Linux 中使用 c_str() 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20219747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com