简体   繁体   English

如何在可执行文件的参数中包含回车符?

[英]How to include a carriage return in an argument to an executable?

I have a simple program that prints out argv character by character, and I want to pass in carriage return ( '\\r' or ASCII# 0x0D) as a program argument. 我有一个简单的程序,逐字符打印argv ,我想传递回车( '\\r'或ASCII#0x0D)作为程序参数。 How do I achieve this in linux OS (Ubuntu)? 如何在linux OS(Ubuntu)中实现这一目标? I am using bash. 我正在使用bash。

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
    int i;  

    for(i = 1; i < argc; i++) {     
        char* curr = argv[i];
        while(*curr != '\0') {
            printf("[%c %x] ", *curr, *curr);
            curr++;
        }
        printf("\n");
    }
    return 0;
}

Assuming our executable program is called test , if the input is : 假设我们的可执行程序称为test ,如果输入是:

./test hi

Then we get 然后我们得到

[h 68] [i 69]

Or if I want to print out newline character, I execute program with command : 或者如果我想打印换行符,我用命令执行程序:

./test '[Enter Pressed]'

Then we get 然后我们得到

[
 0a] 

What should I type for program argument so that it prints out the carriage return? 我应该为程序参数键入什么,以便打印出回车符? Or more generally any ASCII character that are not supported by keyboard? 或者更常见的是键盘不支持的任何ASCII字符?

This actually isn't a C question; 这实际上不是C问题; the question is, how to include a carriage return in an argument to an executable. 问题是,如何在可执行文件的参数中包含回车符。

You haven't indicated what shell you're using, but in many shells, you can write this: 你没有说明你正在使用什么shell,但是在许多shell中,你可以这样写:

./test $'\r'

where $'...' is a special quoting notation that allows you to use C-style escape sequences. 其中$'...'是一种特殊的引号,可以让你使用C风格的转义序列。 (See, for example, §3.1.2.4 "ANSI-C Quoting" in the Bash Reference Manual .) (例如,参见Bash参考手册中的§3.1.2.4“ANSI-C引用” 。)

If your shell does not support that notation, but is POSIX-compliant, you can make use of printf to process the escape sequences for you: 如果你的shell不支持这种表示法,但符合POSIX标准,你可以使用printf为你处理转义序列:

./test "$(printf '\r')"

(See §2.6.3 "Command Substitution" in the Shell Command Language portion of the POSIX spec , plus the documentation for the printf utility .) (参见POSIX规范的Shell命令语言部分中的§2.6.3“命令替换” ,以及printf实用程序的文档 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM