0

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");
1
  • '\\' is a backslash, not a slash.
    – Jim Balter
    Commented Mar 10, 2011 at 23:50

2 Answers 2

5
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);
7
  • forgot the typecast before malloc. Commented Mar 10, 2011 at 23:10
  • @James: casting the return value from malloc() is not necessary in C and, in fact, is frowned upon because it may hide errors (failure to #include <stdlib.h>).
    – pmg
    Commented Mar 10, 2011 at 23:13
  • If I don't typecast in VSC++ I get an error even with stdlib.h included. Commented Mar 10, 2011 at 23:24
  • @James: are you compiling as C or C++? In C, sizeof '#' == sizeof (int); in C++ it very probably isn't. Try it: C versus C++
    – pmg
    Commented Mar 10, 2011 at 23:30
  • I'm pretty sure you can configure the Microsoft compiler to be a C89 compiler. I don't use it though, so I can't help you with the proper way to set it up. If you're writing C, use a C compiler!
    – pmg
    Commented Mar 10, 2011 at 23:44
0

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" */
3
  • I would note that 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.
    – Jim Balter
    Commented Mar 10, 2011 at 23:56
  • I hate Schlemiel too!
    – pmg
    Commented Mar 11, 2011 at 0:05
  • Oops ... s/precise/concise/ .... It's particularly bad when it's the library designer who is the schlemiel. strcat never ever should have been in the library, and strcpy should have been spec'ed to return a ptr to the NUL, not to the beginning of the string. The best solution at this point is to abandon this C language abomination, and yet we see one C homework question after another here.
    – Jim Balter
    Commented Mar 11, 2011 at 0:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.