Как использовать write() и read() в unistd.h
Я пытаюсь использовать функцииread()
иwrite()
из unistd.h, но всякий раз, когда я пытаюсь что-то ввести, это не работает. И мне разрешено использовать только функции из fcntl.h и unistd.h, но не из stdio.h.
Вот мой код:
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd_in = open("/dev/pts/5", O_RDONLY);
int fd_write = open("/dev/pts/log.txt", O_RDWR);
char buf[20];
ssize_t bytes_read;
if (fd_in == -1){
char out[] = "Error in opening file";
write(fd_write, out, sizeof(out));
}
//using a while loop to read from input
while ((bytes_read = read(fd_in, buf, sizeof(buf))) > 0) {
char msg[] = "Block read: \n<%s>\n";
read(fd_write, msg, sizeof(msg));
//continue with other parts
}
}
Проблема в том, что я не получаю желаемого результата для входных данных, которые я предоставляю. Например:
//input
Hello
//output
Block read:
<Hello>
1 ответ
Я написал пример кода, как использоватьread(2)
иwrite(2)
. Я не знаю, нужно ли вам использовать/dev/pts/
или нет. Я им никогда не пользовался, поэтому и сейчас не пользуюсь. Может быть, мой пример все же будет полезен.
Заголовокstring.h
включается только дляstrlen(3)
.
#include <unistd.h>
#include <string.h>
int main (void) {
size_t input_size = 50;
// "+ 1" is for storing '\0'
char buffer[input_size + 1];
// We don't use the return value of
// memset(3), but it's good to know
// anyway that there is one. See also
// https://stackoverflow.com/q/13720428/20276305
memset(buffer, '\0', input_size + 1);
ssize_t bytes_read_count = -1;
ssize_t bytes_written_count = -1;
// Reading
bytes_read_count = read(STDIN_FILENO,
buffer,
input_size);
if (bytes_read_count == -1) {
// No return value checking (and also below). It
// would make little sense here since we exit the
// function directly after write(2), no matter if
// write(2) succeeded or not
write(STDERR_FILENO, "Error1\n", strlen("Error1\n"));
return 1;
}
// We want to be sure to have a proper string, just in
// case we would like to perform more operations on it
// one day. So, we need to explicitly end the array
// with '\0'. We need to do it regardless of the earlier
// memset(3) call because the user might input more
// than input_size, so all the '\0' would be
// overwritten
buffer[input_size] = '\0';
// Writing
bytes_written_count = write(STDOUT_FILENO,
buffer,
bytes_read_count);
if (bytes_written_count == -1) {
write(STDERR_FILENO, "Error2\n", strlen("Error2\n"));
return 1;
}
return 0;
}
Изменить: я добавляю комментарий оmemset(3)
возвращаемое значение, а также убрать его проверку, поскольку она показалась ненужной.