开发者

deleting a file with string in the arguments

How can i remove a file from the dire开发者_开发技巧ctory in c++ ?

I know this function int remove ( const char * filename ) deletes the file whose file name is specified in the argument. But it accepts only char* . Is there any other function in c++ that accepts string as it's argument ?


If you have a std::string, you can get a const char* from it by calling its c_str() member function.

The remove function from <cstdio> is part of the C Standard Library. C has no concept of classes or std::string, hence why the function takes a const char* and not a std::string.


As mentioned by James, you can call remove() with your string C-equivalent, which can be obtained by calling string::c_str(). (Haven't tested this code, but that's the idea):

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main ()
{
    string filename("filename.ext");

    if (remove(filename.c_str()) != 0)
    {
        perror("Error deleting file");
    }
    else
    {
        puts("File successfully deleted");
    }

    return 0;
}


If you can use the Boost libraries, you might want to look into Boost::Filesystem instead. It's a replacement for the file handling routines in <cstdio>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜