How to include a carriage return in an argument to an executable?

五迷三道 提交于 2021-01-27 10:00:24

问题


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. How do I achieve this in linux OS (Ubuntu)? I am using 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 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?


回答1:


This actually isn't a C question; 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:

./test $'\r'

where $'...' is a special quoting notation that allows you to use C-style escape sequences. (See, for example, §3.1.2.4 "ANSI-C Quoting" in the Bash Reference Manual.)

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:

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



来源:https://stackoverflow.com/questions/25922734/how-to-include-a-carriage-return-in-an-argument-to-an-executable

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