【问题标题】:Cant open file using c_str() in linux无法在 linux 中使用 c_str() 打开文件
【发布时间】:2013-11-26 14:26:17
【问题描述】:

在 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()我直接写文件名它可以工作,但每次尝试从文件中获取名称都以文件未打开结束。

我尝试从名称创建 const char*,也不起作用。

【问题讨论】:

  • 您是否将name 设置为合理的值?你检查过调试器吗?
  • 所以您可能没有阅读您认为的内容。也许空间或什么不是。使用调试器或打印出名称。
  • 你知道Linux中的文件名是区分大小写的吗?
  • 一切都指向name 没有你期望的价值。你查过吗,怎么查的?
  • @Eric Finn 是的,我知道,文件名也是小写的。

标签: c++ linux file fstream


【解决方案1】:

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

【讨论】:

  • ASCII 模式下的getline 不应该翻译然后剥离那些(好吧,底层缓冲区进行翻译)?
  • @LightnessRacesinOrbit:它将行尾的主机表示转换为\n。 Windows 实现会剥离 \r,但 Linux 实现不会。
  • @MikeSeymour 确实如此。在 linux 中创建新的data.dat 文件解决了整个问题。
猜你喜欢
  • 2014-09-10
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2019-07-03
  • 2019-01-06
  • 1970-01-01
  • 2013-04-19
相关资源
最近更新 更多