I have a line like the one below, but I need to concat slashes for directories, is there any way to safely concat multiple strings?
// Need to include \\ after windowsDir
FILE *dest = fopen(strcat(windowsDir, filename),"wb");
char *buf = malloc(strlen(windowsDir) + 1 + strlen(filename) + 1); // len + \ + len + \0
sprintf(buf, "%s\\%s", windowsDir, filename);
FILE *dest = fopen(buf, "wb");
free(buf);
malloc()
is not necessary in C
and, in fact, is frowned upon because it may hide errors (failure to #include <stdlib.h>
).
C
, use a C
compiler!
Supposing there is enough space all around, this works
strcpy(buff, "C:\\foobar");
strcpy(value, "file.txt");
strcat(strcat(buff, "\\"), value);
/* buff now has "C:\\foobar\\file.txt" */
sprintf
(or better, snprintf
) is more general, more precise, and doesn't have to rescan the previous string for every append ... not a problem here, but strcat
doesn't scale.
Commented
Mar 10, 2011 at 23:56
'\\'
is a backslash, not a slash.