【问题标题】:c++ remove and rename commands [duplicate]c ++删除和重命名命令[重复]
【发布时间】:2015-07-01 17:12:51
【问题描述】:

我正在使用 aide 和 cppdroid for android 在 c++ 中进行编码。我在文件重命名和删除命令方面遇到了一些问题。我的猜测是你不能这样做。我有用户输入,但不知道他们会输入什么,所以我需要一个变量或字符串来输入文件的路径名。

remove("/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/" + output2 + ".txt");             

rename("/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/temp.txt","/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/" + output2 + ".txt");

是我使用的代码,它有错误。有没有其他方法可以写这个,所以我可以添加 output2 来定位文件?

错误是:

NDK:无法将参数 '1' 的 'std::basic_string' 转换为 'char const*' 到 'int remove(char const*)'

【问题讨论】:

    标签: android c++


    【解决方案1】:

    NDK:无法将参数 '1' 的 'std::basic_string' 转换为 'char const*' 到 'int remove(char const*)'

    你的函数需要一个字符数组,但你传递给它一个字符串对象。你需要在你的字符串对象上调用.c_str()

    std::basic_string::c_str()

    所以"/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/" + output2 + ".txt" 本身需要是一个字符数组。

    实现此目的的一种方法是将其存储为字符串,然后将c_str() 传递给函数。

    std::string loc{"/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/" + output2 + ".txt"};
    
    remove(loc.c_str());
    

    【讨论】:

    • 这会崩溃(或更糟)。
    • 是因为我将一个 c 字符串附加到一个字符串文字并且刚刚捕获它,还是我错过了什么?
    • const char * 加在一起绝不是一个好主意。请参阅我在 cmets 中指向问题的重复链接,了解应该如何完成。
    • 基本上加点( )就对了。
    • 认为就是这样。我修正了我的答案以匹配@NathanOliver
    【解决方案2】:

    好的,这是没有错误的工作。

    std::string loc ("/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/" + output2 + ".txt");
    remove(loc.c_str());
    std::string loc1("/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/temp.txt");
    std::string loc2("/storage/emulated/0/MyGame/MyHackGame/jni/gameFiles/" + output2 + ".txt");
    rename(loc1.c_str() , loc2.c_str());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2012-10-14
      • 2021-12-11
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多