[英]Weird string result
My program should open a file, the file path is retrieved from the command line using argv[1]
. 我的程序应该打开一个文件,使用
argv[1]
从命令行检索文件路径。
I then try to open the file using fopen but my program crashes because the filepath I use doesn't contain double backslashes so fopen doesn't work. 然后,我尝试使用fopen打开文件,但程序崩溃,因为我使用的文件路径不包含双反斜杠,因此fopen无法正常工作。
I've tried to write my own convert function and using print to check the result looked good at first sight. 我试图编写自己的convert函数,并使用print来检查结果,乍一看看起来还不错。
The problem is that when I use the returned const char* as argument it gives me a weird result.. my code: 问题是,当我使用返回的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;
}
Opening a DBC file with my program gives me the following result: 用我的程序打开一个DBC文件会得到以下结果:
D:\\Achievement.dbc
a
So it looks like const char* file
only contains 1 char of the file path, why? 所以看起来
const char* file
只包含文件路径的1个char,为什么?
You do not need the ConvertToPath function at all. 您根本不需要ConvertToPath函数。 Double backslashes are only needed in string literals.
仅在字符串文字中需要双反斜杠。 Never in variables such as a std::string.
绝对不要在std :: string之类的变量中使用。
I compiled your code on Linux and can not replicate your result 我在Linux上编译了您的代码,无法复制结果
Running ./filereader "D:\\\\Achievement.dbc"
results in 运行
./filereader "D:\\\\Achievement.dbc"
导致
D:\\Achievement.dbc
D:\\Achievement.dbc
Running ./filereader "D:\\\\\\\\Achievement.dbc"
results in 运行
./filereader "D:\\\\\\\\Achievement.dbc"
导致
D:\\\\Achievement.dbc
D:\\\\Achievement.dbc
The later is what you want because command line arguments need to be escaped. 后面就是您想要的,因为需要对命令行参数进行转义。 Then you can remove the
ConvertToPath
. 然后,您可以删除
ConvertToPath
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.