奇怪的字符串结果

时间:2014-04-27 19:54:28

标签: c++ string file

我的程序应该打开一个文件,使用argv[1]从命令行检索文件路径。

然后我尝试使用fopen打开文件,但我的程序崩溃,因为我使用的文件路径不包含双反斜杠,所以fopen不起作用。

我试图编写自己的转换功能并使用print检查结果看起来很好看。

问题是,当我使用返回的const char *作为参数时,它给了我一个奇怪的结果..我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string>


const char* ConvertToPath(std::string path)
{
    std::string newpath = "";
    for(unsigned int i = 0; i < path.length(); ++i)
    {
        if(path[i] == '\\')
        {
            newpath += "\\\\";
        }
        else
        {
            newpath += path[i];
        }
    }
    printf("%s \n", newpath.c_str());
    return newpath.c_str();
}

bool OpenDBC(const char* path)
{
    const char* file = ConvertToPath(path);
    printf("%s \n", file);
    FILE* dbc = fopen(file, "rbw");
    if (!dbc)
        return false;
    return true;
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        printf("Error, expected DBC file.");
        getchar();
        return -1;
    }

    if (!OpenDBC(argv[1]))
    {
        printf("There was an error opening the DBC file.");
        getchar();
        return -1;
    }
    getchar();
    return 0;
}

使用我的程序打开DBC文件会给我以下结果:

D:\\Achievement.dbc
a

所以看起来const char* file只包含文件路径的1个字符,为什么?

1 个答案:

答案 0 :(得分:1)

根本不需要ConvertToPath功能。只有字符串文字才需要双反斜杠。从不在诸如std :: string之类的变量中。

相关问题