【问题标题】:Deleting a file with name created using a string variable删除名称使用字符串变量创建的文件
【发布时间】:2013-11-17 11:51:59
【问题描述】:

我正在编写一个函数,让用户有机会更改他们的用户名。为此,我试图重命名存储数据的文件。我想出了一种方法,虽然不太奏效,但我认为我已经接近了。

文件名最初是这样创建的 -

std::cout << "Please enter a username: ";
std::getline (std::cin, username);

std::ofstream fout (username + ".txt");

效果很好。然后如果他们以后选择更改用户名

std::cout << "Please type in your new username." << std::endl;
std::getline (std::cin, newUsername);

std::ofstream fout (newUsername + ".txt");
// I copied the contents of username.txt to newUsername.txt here

这又可以正常工作了。

问题出在下面。

问题在于删除原始文件,更具体地说是添加文件扩展名.txt时

我已经为 remove() 功能添加了#include 并将 .c_str() 添加到用户名,因为我相信 remover () 只会采用 C 字符串(char*),而不是 C++ 字符串。

remove(username.c_str() + ".txt"); // error expression must have integral or enum type         referring to ".txt".

提前感谢大家的时间

【问题讨论】:

    标签: c++ string file


    【解决方案1】:

    够简单

    remove((username + ".txt").c_str());
    

    username + ".txt" 的返回值被称为 临时(因为它是一个未命名的值),但没有任何内容表明您不能在临时对象。

    【讨论】:

    • 感谢删除错误,所以现在程序编译了,但由于某种原因它仍然没有删除文件 username.txt?你能想出它可能没有的任何原因,或者我可以发布任何可能有用的额外代码。
    • 这可能有很多原因。我们正在讨论您的程序如何与操作系统交互,因此很难给出明确的建议。一些可能的原因,文件仍然打开(你忘了关闭它吗?),你没有删除它的权限,程序在你期望的不同目录中寻找文件,程序确实删除了它但随后您的程序会重新创建它。还有很多其他原因。
    • Remove成功返回0,所以首先应该检查remove的返回值。
    • 我应该添加一个明显的可能性,变量username 没有您认为的值,这可能是最有可能的。
    • 是的,我忘记关闭文件了。坚持了几个小时,非常感谢
    【解决方案2】:

    remove 将const char* 作为参数,您不能使用+ 运算符将两个const char*s 相加。因此,解决方案是将它们添加为字符串,然后在结果上调用c_str()。

    remove((username + std::string(".txt")).c_str());
    

    【讨论】:

      【解决方案3】:

      你的问题在这里:

      remove(username.c_str() + ".txt"); // error expression must have integral or enum type         referring to ".txt".
      

      添加两个char*s 不会产生string。

      这可能是更好的方法:

      auto filename = username + ".txt"
      remove(filename.c_str())
      

      【讨论】:

        【解决方案4】:

        你的问题在这里:

        remove(username.c_str() + ".txt"); // error expression must have integral or enum type         referring to ".txt".
        

        添加两个const char*s 不会产生(std::)string。

        这可能是更好的方法:

        auto filename = username + ".txt"
        remove(filename.c_str())
        

        请注意,这会产生一个相对文件名,而绝对文件名可能更可取,具体取决于它的调用方式。

        【讨论】:

          猜你喜欢
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 2014-12-13
          • 1970-01-01
          • 2021-02-11
          • 1970-01-01
          相关资源
          最近更新 更多