如何解释C中命令行参数中的特殊字符? [英] How to interpret special characters in command line argument in C?

查看:24
本文介绍了如何解释C中命令行参数中的特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个问题:

假设我们编写了一个简单的程序,它接受命令行参数并打印到一个文件中.如果用户输入

Suppose we write a simple program which takes in command line arguments and prints to a file. If the user enters

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

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

bash 回复

!0: 事件不是找到了.

!0: event not found.

如果用户不知道使用引号 ('') 或转义字符 ('\') 之类的东西,我该如何处理这些东西而不是 bash 将其理解为命令?

Without the user knowing things like using quotes ('') or escape characters ('\'), how do I handle this stuff instead of bash understanding it as a command?

第二个问题:

一旦我得到这些参数,我如何将它们解释为特殊字符而不是字符序列.(即.\t 是制表符,而不是 '\''t')

Once I get these arguments, how do I interpret them as special characters and not sequences of characters. (ie. \t is tab, not '\''t')

也就是说,如何确保程序将其写入文件:

That is, how do make sure that the program writes this to the file:

Hello!0
 w%orl    !@#y

而不是

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

推荐答案

关于第二个问题:正如@Jims 所说,你可以使用 printf(1) 来打印字符串.好主意,但请注意,这仅会起作用,因为您(似乎)想要识别的转义符,例如 \t\n 与那些相同printf 识别.

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.

这些转义很常见,但它们没有什么基本的东西,所以一般对你的问题的回答——以及如果你想识别 printf 没有的转义的答案——适用于你的程序来解释它们.执行此操作的类 C 代码类似于:

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).

这篇关于如何解释C中命令行参数中的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆