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

女生的网名这么多〃 提交于 2019-12-02 13:27:29

Regarding the second problem: as @Jims said, you could use printf(1) to print the string. Good idea, but be aware that that would work only because the escapes you (appear to) want to recognise, like \t and \n, are the same as the ones that printf recognises.

These escapes are common, but there's nothing fundamental about them, so the general answer to your question – and the answer if you want to recognise an escape that printf doesn't – is for your program to interpret them. The C-like code to do that would be something like:

char *arg = "foo\\tbar\\n"; /* the doubled backslashes are to make this valid C */
int arglen = strlen(arg);
for (i=0; i<arglen; i++) {
    if (arg[i] == '\\') { // we've spotted an escape
        // interpret a backslash escape
        i++; // we should check for EOS here...
        switch (arg[i]) {
          case 'n': putchar('\n'); break;
          case 't': putchar('\t'); break;
          // etc
         }
     } else {
         // ordinary character: just output it
         putchar(arg[i]);
     }
 }

(insert error handling and good style, to taste).

You can't get bash to stop parsing a command line as a command line. In your particular case, set +H would disable history expansion, thus allowing !0 as a literal, but a command would still fail if you included (parenthesis), $variables, #comments, ampersand & and a dozen other elements of shell syntax.

Note that this only applies to the parsing stage of the shell, not for any data that is passed literally into execve or similar.

Either make the user quote the data ('single quotes' will take care of everything except other single quotes), or make your program read the data itself so that the interaction goes

$ writetofile
Please enter your gibberish and press enter: Hello!0\n w%orl\t!@#y
Thank you for your eloquent contribution.
$

First problem: Use single quotes. ie: writetofile 'Hello!0\n w%orl\t!@#y'

Second problem: Use printf.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!