Simple Example Program For Read And Write System Call

Simple Example For Read System Call

here's a simple example of how to use the read system call in Linux:

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

int main() {
char buffer[100];
int num_bytes = read(STDIN_FILENO, buffer, 100);
printf("Read %d bytes from stdin: %s\n", num_bytes, buffer);
return 0;
}

In this example, we include the necessary headers (stdio.h and unistd.h) and declare a character buffer of size 100 to store the input we read from the user.

Then, we call the read system call with three arguments: the file descriptor of the input stream (STDIN_FILENO), the buffer to read the input into (buffer), and the maximum number of bytes to read (100).

The read system call will block until input is available, and will then read up to 100 bytes from the input stream into buffer. The number of bytes actually read is returned by the function and stored in the num_bytes variable.

Finally, we print out the number of bytes read along with the input we read from the user using printf.

Note that this is just a simple example and in practice, you would want to handle errors and edge cases properly.

Simple Example For Write System Call

here's a simple example for the write system call in Linux:

#include <unistd.h>
#include <fcntl.h>

int main() {
int fd = open("output.txt", O_WRONLY | O_CREAT, 0644);
write(fd, "Hello, World!", 13);
close(fd);
return 0;
}

In this example, we're using the write system call to write the string "Hello, World!" to a file called output.txt. First, we open the file using the open system call with the O_WRONLY flag (to open it for writing only) and the O_CREAT flag (to create the file if it doesn't already exist). The 0644 argument specifies the file permissions.

Next, we use the write system call to write the string to the file. The first argument to write is the file descriptor returned by open. The second argument is a pointer to the buffer containing the data to be written, and the third argument is the number of bytes to write (in this case, 13, which is the length of the string).

Finally, we close the file descriptor using the close system call.

When we run this program, it will create a new file called output.txt in the same directory as the program, write the string "Hello, World!" to it, and then close the file.