使函数接受字符串变量内的路径

making function accept the path that's inside the string variable

本文关键字:路径 变量 字符串 函数      更新时间:2023-10-16

我有一个名为b1的字符串变量。

该变量保存路径。

我需要让"删除"函数从变量中获取该路径b1

这是我的代码...

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>

using namespace std;
string a1 = "W:\ftp\4CS\DL\";
string a2;
int getdir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp = opendir(dir.c_str())) == NULL)
    {
    cout << "Error(" << errno << ") opening " << dir << endl;
    return errno;
    }
    while ((dirp = readdir(dp)) != NULL) {
std::string fname = dirp->d_name;
if(fname.find("te") != std::string::npos)
    files.push_back(fname);
}
}
int main()
{
string catcher;
    string dir = string(a1);
    vector<string> files = vector<string>();
    getdir(dir,files);
    for (unsigned int i = 0; i < files.size();)
{
        //cout << files[i] << endl;
        a2 = files[i];
        cout << a2 << endl;
string b1 = a1 + a2;
cout << b1 << endl;
//const int result = remove("W:\ftp\4CS\DL\testng it.txt");
char filename[] = b1;
/*  Deletes the file if exists */
if (remove(filename) != 0)
    perror("File deletion failed");
else
    cout << "File deleted successfully";
return 0;
i++;
}
    system("pause");
    return 0;
}

简单

remove(b1.c_str());

调用 c_str(( 从C++字符串中获取指向 C 字符串的指针。