Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert a #defined string into a system() command? (win32)

Here is an overly simplified version of what I am trying to do:

#define LOGDIRECTORY C:\\logs\\
system("mkdir LOGDIRECTORY");

However the preprocessor, instead of swapping out the defined name is not. Instead the system command actually thinks LOGDIRECTORY is the name, and thus is shooting me errors when starting the program.

I know it's wrong and there must be something I can do with the " marks or other characters to specify what I want, but I can't figure it out. I don't want to hardcode the directory and file names because someone may want to change them in the future and it would be much easier to change a define than the whole function etc.

PS, I am coding this in plain C.


2 Answers

#define LOGDIRECTORY C:\\logs\\
#define DEF2STR(x) #x
system("mkdir " DEF2STR(LOGDIRECTORY));
#define LOGDIRECTORY_WITH_QUOTES "C:\\logs\\"
system("mkdir " LOGDIRECTORY_WITH_QUOTES);

In C, you can do simple string concatenation by writing two string literals with no operator in between. "A" "B" will be converted to "AB" at compile time. You can also use this for splitting a long string to multiple lines.

printf("a very long "
"string indeed");

To convert the define to a proper string, use the pound sign (#) in a macro or skip the whole thing and include the quotes in the define itself.

like image 51
kichik Avatar answered Mar 04 '26 13:03

kichik


If you were compiling with GCC, you would have no choice but to wrap the define with quotes since the final trailing backslash would be interpreted as a line continuation character, and if that does not cause an error on its own, the penultimate backslash would likely raise a error. However, if you chose to just get rid of the trailing backslash, you'd still need to use two levels of stringification macros, or your syscal would be "mkdir LOGDIRECTORY". See http://gcc.gnu.org/onlinedocs/cpp/Stringification.html

So the above example would become:

#define LOGDIRECTORY C:\\logs
#define DEF2STR(x) #x
#define STR(x) DEF2STR(x)
system("mkdir " STR(LOGDIRECTORY));
like image 28
Mike Godin Avatar answered Mar 04 '26 14:03

Mike Godin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!