简体   繁体   中英

string concatenation using #define in C

I am trying to concatenate strings and 2/3 strings are paths and are defined in #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

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. That's why the resulting string doesn't exceed 4 characters (including the null-terminator). Use sizeof path_of_executable instead.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM