Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass in a null character in a command line argument in C?

I would still like to know how to pass in a null character as a command line argument, maybe so that a single string can be passed in as an argument in the form:

"to\0be\0or\0not\0to\0be\0"

And then parse it. However the program would treat this string as:

"to\\0be\\0or\\0not\\0to\\0be\\0"

How can I work around this? Is there any way?

like image 533
Tom Avatar asked Feb 17 '10 18:02

Tom


People also ask

How do I enter a null character in terminal?

In Linux, any special character can be literally inserted on the terminal by pressing Ctrl + v followed by the actual symbol. null is usually ^@ where ^ stands for Ctrl and @ for whatever combination on your keyboard layout that produces @ .

Can a character be null in C?

The Null character in the C programming language is used to terminate the character strings. In other words, the Null character is used to represent the end of the string or end of an array or other concepts in C. The end of the character string or the NULL byte is represented by '0' or '\0' or simply NULL.

How do you represent a null character?

The null character is often represented as the escape sequence \0 in source code , string literals or character constants.

Are command line arguments null terminated in C?

Yes. The non-null pointers in the argv array point to C strings, which are by definition null terminated.


2 Answers

C strings are null-terminated, so passing strings containing NUL characters is not possible in C. :-P

Now, if you just wanted a way to convert \0 (in the user input, i.e., "\\0" as a C string) into actual NUL characters, that's another matter. In that case, your program just needs a parser to treat \0 as separators.

like image 43
Chris Jester-Young Avatar answered Nov 16 '22 18:11

Chris Jester-Young


You cannot.

The C program receives arguments as zero-terminated strings. Such a string cannot contain a null character, by definition.

If you want to pass a null character, then you must somewhat encode it with some syntax, and your C program must then decode it by interpreting that syntax.

like image 65
Thomas Pornin Avatar answered Nov 16 '22 17:11

Thomas Pornin