pistal
pistal

Reputation: 2456

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?

Upvotes: 0

Views: 341

Answers (3)

Jimbo
Jimbo

Reputation: 4515

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)

Upvotes: 1

Curt
Curt

Reputation: 5722

Replace sizeof 256 with sizeof( path_of_executable )

Upvotes: 2

Kninnug
Kninnug

Reputation: 8053

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.

Upvotes: 2

Related Questions