Sunday, 15 September 2013

bash - How to interpret special characters in command line argument in C? -



bash - How to interpret special characters in command line argument in C? -

first problem:

suppose write simple programme takes in command line arguments , prints file. if user enters

writetofile hello!0\n w%orl\t!@#y

bash replies with

!0: event not found.

without user knowing things using quotes ('') or escape characters ('\'), how handle stuff instead of bash understanding command?

second problem:

once these arguments, how interpret them special characters , not sequences of characters. (ie. \t tab, not '\''t')

that is, how create sure programme writes file:

hello!0 w%orl !@#y

and not

hello!0\n w%orl\t!@#y

regarding sec problem: @jims said, utilize printf(1) print string. idea, aware that work because escapes (appear to) want recognise, \t , \n, same ones printf recognises.

these escapes common, there's nil fundamental them, general reply question – , reply if want recognise escape printf doesn't – programme interpret them. c-like code like:

char *arg = "foo\\tbar\\n"; /* doubled backslashes create valid c */ int arglen = strlen(arg); (i=0; i<arglen; i++) { if (arg[i] == '\\') { // we've spotted escape // interpret backslash escape i++; // should check eos here... switch (arg[i]) { case 'n': putchar('\n'); break; case 't': putchar('\t'); break; // etc } } else { // ordinary character: output putchar(arg[i]); } }

(insert error handling , style, taste).

c bash special-characters command-line-arguments argv

No comments:

Post a Comment