Link to home
Start Free TrialLog in
Avatar of diarmaid
diarmaid

asked on

Find + escape(replace) a (\)character in a path + filename from command line.

I have written a small program that will be run on Win NT4 and W2k from a batch file.
I am using _findfirst to get the file attributes and I then open the file using fopen(name, a+) to read the number of records and I then append this info as a new record at the end of the file. (all works ok)

I want to be able to run the program from within the batch script using something like
program.exe c:\dir1\dir2\dirtest\filename.txt

I will copy the path+filename into a variable (say char *test) from argv[1].
I then need to escape(replace) the '\' characters in the string with '\\' so _findfirst and fopen will work correctly.
ie. I need test to contain c:\\dir1\\dir2\\dirtest\\filename.txt

I hope ive explained this clear enough as its been a while since ive been writing c.

int main(int argc, char* argv[])
{
  char *test;
  *test = argv[1]; //test now contains c:\dir1\dir2\dirtest\filename.txt
  //need to parse test so it contains c:\\dir1\\dir2\\dirtest\\filename.txt
...
...
}

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi diarmaid,

jkr's correct.

The backslash tells the compiler, "do not place this character (the backslash) in the string, insert the next character without interpretting it".  The entire backslash thing came to be so that you could put quotes into your message.  "This message contains a double quote (\")".  Without the backslash the quote in the parentheses would be interpretted as the end of string and you'd get a compilation error.

The C compiler interprets the backslash so that whatever follows it is placed into the string without question.  When your string contains double backslashes, the compiler treats the first one as an escape character and insterts the second into the actual string -- which is the effect that you want.

Kent
Avatar of diarmaid
diarmaid

ASKER

Thanks, as i said its been a while, forgot about that.