[英]string concatenation using #define in C
I am trying to concatenate strings and 2/3
strings are paths and are defined in #define
我正在尝试连接字符串,而2/3
字符串是路径,并在#define
中定义
For example: 例如:
#define BASE_PATH "foo/bar"
#define BIN_PATH "baz/bin"
I want to be able to direct to the predefined paths. 我希望能够定向到预定义的路径。 An example use case would be viewing the contents of that folder. 一个示例用例将是查看该文件夹的内容。
char path_of_executable[256];
printf ("%s \n",executable);
snprintf(path_of_executable, sizeof 256, "%s,%s,%s",BASE_PATH,executable,BIN_PATH);
printf("%s \n",path_of_executable);
chdir(path_of_executable);
execlp("ls","ls","-l",NULL);
The path_of_executable is printed out as /fo
path_of_executable输出为/fo
I am not able to direct to that path but instead the files in the current folder are printed out. 我无法定向到该路径,而是打印出当前文件夹中的文件。 Any idea what could be the problem? 知道可能是什么问题吗?
You're using sizeof 256
, which translates to sizeof int
, which apparently 4 on your platform. 您正在使用sizeof 256
,它转换为sizeof int
,显然在您的平台上为4。 That's why the resulting string doesn't exceed 4 characters (including the null-terminator). 这就是为什么结果字符串不超过4个字符(包括null终止符)的原因。 Use sizeof path_of_executable
instead. 请改用sizeof path_of_executable
。
将sizeof 256
替换为sizeof( path_of_executable )
In the line 在行中
snprintf(path_of_executable, sizeof 256, "%s,%s,%s",BASE_PATH,executable,BIN_PATH);
replace sizeof 256
with sizeof(path_of_executable) 将sizeof 256
替换为sizeof(path_of_executable)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.