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. 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);
Sign up to request clarification or add additional context in comments.

7 Comments

forgot the typecast before malloc.
@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>).
If I don't typecast in VSC++ I get an error even with stdlib.h included.
@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++
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!
|
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 Comments

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.
I hate Schlemiel too!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.