magix said:
I have
char* str1 = "d:\temp\data\test.txt"
I want to replace all the "\" to be "\\", so that
the string will have "d:\\temp\\data\\test.txt"
You can't change the above string at all. What you have
there is a pointer that points to memory that you are
not allowed to change - it could be read-only memory.
Now, if you change the definitionof 'str1' to
char str1[ ] = "d:\temp\data\test.txt";
things already look a bit better since now 'str1' isn't
just a pointer but a real array, initialized with
the string. And that's now something you can change.
But you couldn't double just one character in that
array since it simply isn't large enough to hold
one more character. To add something to the string
you would first have to get hold of memory where
the resulting string would fit in.
But there is another problems. There's not a single
backslash in that string! E.g. "\t" isn't a backslash
followed by the character 't' but it's the escape
sequence for the tab character. And '\d' is not even
a valid escape sequence, so the compiler will try to
warn you and drop the backslash. If you try to print
that string anyway you will get something like
d: empdata est.txt
(the details depending on the tab settings on your
machine). So there actually isn't a single backslash
character in your 'str1' since the single backslash
characters you wrote in there are always taken to
"escape" the following character. Whenever you
see a backslash in a string in C (or a character
constant like '\t') remember that this is just a
kind of "operator", changing the meaning of the
following character in the string. And to get a
real baclslash character you have to write '\\'
since the backslash "escapes" itself.
Thus if you want backslashes in the string you have to
double them already when you write the string in order
to end up with single backslashes within it at all.
Putting in two backslashes in a row results in a
single backslash character in the string. If you do
that like this
char str1[ ] = "d:\\temp\\data\\test.txt";
then 'str1' contains three (not six) backslashes. And
I guess you're not really interested in doubling those
anymore.
Regards, Jens
PS. If I am not completely misinformed you can also
use a normal slash '/' as a path separator under
Windows (what I guess you're using from the 'd:'
at the start of the string) in a C program. So if
this is supposed to be a path you could use
char str1[ ] = "d:/temp/data/test.txt";
and pass that to e.g. fopen() and it should still
work as intended.