1
4

4 回答 4

4

我是否可以建议使用 C++ 开始,以及 (Boost) Filesystem 以获得最大收益:

#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main(int argc, const char *argv[])
{
    const std::vector<std::string> args { argv, argv+argc };

    path program(args.front());
    program = canonical(program);
    std::cout << (program.parent_path() / "docs").native();
}

这将使用平台的路径分隔符,知道如何翻译“有趣”的路径(例如包含..\..\或 UNC 路径)。

于 2013-07-10T18:27:05.383 回答
1

你的方式:

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    int pathSize = 0;

    char* pathEnd = &argv[0][0];
    while(argv[0][pathSize] != '\0') {
        if(argv[0][pathSize++] == '/')
            pathEnd = &argv[0][0] + pathSize;
    }

    pathSize = pathEnd - &argv[0][0];
    char *path = new char[pathSize + 5]; //make room for "docs/"
    for(int i = 0; i < pathSize; i++) 
        path[i] = argv[0][i];

    char append[] = "docs/";
    for(int i = 0; i < 5; i++) 
        path[pathSize+i] = append[i];

    cout << "Documents Path: " << path << endl;
    function_expecting_charptr(path);

    delete[] path;
    return 0;
}

Sane C方式:

#include <iostream>
using namespace std;

int main(int argc, char** argv) {

    char* pathEnd = strrchr(argv[0], '/');
    if (pathEnd == NULL)
        pathEnd = argv[0];
    int pathSize = (pathEnd-argv[0]) + 5; //room for "docs/"

    char *path = new char[pathSize];
    if (pathSize)
        strncpy(path, argv[0], pathSize+1);
    strcat(path, "docs/");

    cout << "Documents Path: " << path << endl;
    function_expecting_charptr(path);

    delete[] path;
    return 0;
}

C++方式:

#include <iostream>
#include <string>

int main(int argc, char** argv) {
    std::string path = argv[0];

    size_t sep = path.find('/');
    if (sep != std::string::npos)
        path.erase(sep+1);
    else
        path.clear();

    path += "docs/";
    std::cout << "Documents Path: " << path << endl;
    function_expecting_charptr(path.c_str());

    return 0;
}

请注意, argv[0] 拥有一个实现定义的值,尤其是在 *nix 环境中,不能保证拥有任何有用的东西。传递给程序的第一个参数在 argv[1] 中。

于 2013-07-10T18:31:13.710 回答
1

这样的事情应该这样做(完全未经测试):

const char* end = strrchr(argv[0], '/');
std::string docpath = end ? std::string(argv[0], end) : std::string(".");
docpath += '/docs/';
于 2013-07-10T18:27:11.423 回答
0

我将你们的一些想法结合到这个紧凑的代码中:

#include <iostream>
#include <cstring>
using namespace std;

int main(int argc, char** argv) {
    const string path_this = argv[0];
    const string path = path_this.substr(0, strrchr(argv[0], '/') - argv[0] +1);
    const string path_docs = path + "docs/";
    cout << "Documents Path: " << path_docs << endl;
    return 0;
}

要从中获取字符数组,我可以运行“path_docs.c_str()”。

学分:@MooingDuck@MarkB谷歌

于 2013-07-10T19:38:37.323 回答