Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 355
Harry Cho Avatar asked Jan 10 '23 18:01

Harry Cho


1 Answers

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

like image 52
ruakh Avatar answered Apr 09 '23 11:04

ruakh