ButterMyBitter
ButterMyBitter

Reputation: 93

How to output single character in C with write?

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.

Upvotes: 6

Views: 20824

Answers (3)

Zibri
Zibri

Reputation: 9857

Also valid is:

#include <stdio.h>
#include <unistd.h>

int main(void) {
    char  b[1] = {'b'};
    write(STDOUT_FILENO, b, 1);
    return 0;
}

Or:

#include <stdio.h>
#include <unistd.h>

int main(void) {
    char  b[1] = "b";
    write(STDOUT_FILENO, b, 1);
    return 0;
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726879

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.

Upvotes: 7

Sourav Ghosh
Sourav Ghosh

Reputation: 134366

Let's see the man page of write(), which says,

ssize_t write(int fd, const void *buf, size_t count);

Description

write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.

As per your requirement, you need to pass an address of a buffer containing b to print to standard output.

Let's see some code along with, shall we?

#include <stdio.h>
#include <unistd.h>

int main(void) {
    char  b = 'b';
    write(STDOUT_FILENO, &b, 1);
    return 0;
}

Let me explain. Here, the STDOUT_FILENO is the file descriptior for standard output as defined in unistd.h, &b is the address of the buffer containing 'b' and the number of bytes is 1.

Upvotes: 3

Related Questions