【问题标题】:Weird string result奇怪的字符串结果
【发布时间】:2014-04-27 19:54:27
【问题描述】:

我的程序应该打开一个文件,文件路径是使用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 个字符,为什么?

【问题讨论】:

  • 您依赖于未定义的行为,从本地字符串返回 c_str() 是一个非常糟糕的主意。只需返回字符串并从OpenDBC 内部调用c_str()
  • @Chnossos 的评论是正确的,但我也很好奇这个说法:“我的程序崩溃,因为我使用的文件路径不包含双反斜杠,所以 fopen 不起作用”。除非在程序的源代码中指定了路径,否则通常不需要转义反斜杠。
  • 您根本不需要ConvertToPath,只需致电fopen(argv[1]) 即可查看结果。

标签: c++ string file


【解决方案1】:

您根本不需要 ConvertToPath 函数。仅在字符串文字中才需要双反斜杠。永远不要在 std::string 等变量中。

【讨论】:

    【解决方案2】:

    我在 Linux 上编译了你的代码,无法复制你的结果

    运行 ./filereader "D:\\Achievement.dbc" 结果

    D:\\Achievement.dbc
    D:\\Achievement.dbc
    

    运行./filereader "D:\\\\Achievement.dbc" 导致

    D:\\\\Achievement.dbc 
    D:\\\\Achievement.dbc 
    

    后者是您想要的,因为需要对命令行参数进行转义。然后你可以删除ConvertToPath

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多