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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With