Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display characters in a write() funtion C

I’m trying to display a certain way of outputting information. Right now I’m using Vim in the shell of Linux

  1. to display a ‘char’ written in a function
  2. it has to be portrayed like this
void ft_putchar(char c);

AND it has to be displayed via another function like so

write(1, &c, 1);

Right now I have no idea what I’m doing wrong, but I have many error codes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried putting both functions into the main() one but the only thing I receive while trying to compile are errors.
this is my code:

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

void ft_putchar(char c);
{
        write(1, &c , 1)
}

int main(){
        ft_putchar('a');
}

and this is the error code –

└─$ gcc ft_putchar.c
ft_putchar.c:5:1: error: expected identifier or ‘(’ before ‘{’ token
5 | {
| ^

>Solution :

Firstly, ensure you have included the necessary header for the write function. The write function is defined in unistd.h, so you need to include this header at the top of your file.

Here’s a simple example of how you might define ft_putchar and use it in a main function:

#include <unistd.h>

// Function declaration
void ft_putchar(char c);

int main() {
    // Example usage of ft_putchar
    ft_putchar('H');
    ft_putchar('e');
    ft_putchar('l');
    ft_putchar('l');
    ft_putchar('o');
    ft_putchar('\n');

    return 0;
}

// Function definition
void ft_putchar(char c) {
    write(1, &c, 1);
}

In this example:
The ft_putchar function takes a single character c as its parameter.
It then calls write, with 1 as the first argument to specify the file descriptor for standard output (stdout), &c to pass the address of the character to write (since write expects a pointer), and 1 as the third argument to specify that
we want to write one byte (since a char in C is typically one byte).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading