How do I output a single character in C with writing?

Can anyone please instruct me on how to print a single letter like "b" in C using only the not printf function.

I'm pretty sure he uses

#include <unistd.h>

      

Could you also tell me how write properties work? I really do not understand

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

      

Could some of you guys throw some tips for C beginners?

I am using UNIX.

+3


source to share


2 answers


You found your function, now you need to pass the required 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 really wanted to use stdout. How do I write a version to display the entire alphabet?

You can use a predefined constant for stdout. It's called STDOUT_FILENO

.



If you want to spell out the entire alphabet, you can do it like this:

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

      

Demo version

+4


source


See the man page write()

that says:

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

Description

write()

writes up to count

bytes from the specified in the buffer buf

to the file specified by the file descriptor fd

.

As per your requirement, you need to pass the address of the buffer containing b

to print to stdout.



Let's look at some code along with?

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

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

      

Let me explain. Here, STDOUT_FILENO

- a file descriptor for the standard output, as defined in unistd.h

, &b

- a buffer address, comprising 'b'

, as the number of bytes - 1 ..

+3


source







All Articles