Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output single character in C with write?

Tags:

c

function

unix

Could someone instruct me on how to print a single letter, for example "b" in C while using only the write function (not printf).

I'm pretty sure it uses

#include <unistd.h>

Could you also tell me how the write properties work? I don't really understand

int  write(  int  handle,  void  *buffer,  int  nbyte  );

Could some of you guys toss in a few C beginner tips as well?

I am using UNIX.

like image 619
ButterMyBitter Avatar asked Aug 07 '15 19:08

ButterMyBitter


People also ask

How do you read and write single character in C?

The simplest of the console I/O functions are getche (), which reads a character from the keyboard, and putchar (), which prints a character to the screen. The getche () function works on until a key is pressed and then, returns its value. The key pressed is also echoed to the screen automatically.

What is %d %f %s in C?

The first argument to printf is a string of identifiers. %s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0]. Follow this answer to receive notifications.

What does %% mean in C?

It is an escape sequence. As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.


1 Answers

You have found your function, all you need now is to pass it proper parameters:

int handle = open("myfile.bin", O_WRONLY);
//... You need to check the result here
int count = write(handle, "b", 1); // Pass a single character
if (count == 1) {
    printf("Success!");
}

I did indeed want to use stdout. How do I write a version to display the whole alphabet?

You could use a pre-defined constant for stdout. It is called STDOUT_FILENO.

If you would like to write out the whole alphabet, you could do it like this:

for (char c = 'A' ; c <= 'Z' ; c++) {
    write(STDOUT_FILENO, &c, 1);
}

Demo.

like image 184
Sergey Kalinichenko Avatar answered Sep 28 '22 09:09

Sergey Kalinichenko