我试图使用unistd.h中的read()
和write()
函数,但是每当我尝试输入任何内容时,它都无法工作。我只能使用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>
发布于 2022-10-28 21:17:21
我编写了如何使用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)
返回值的注释,还删除了检查它,因为它似乎没有必要。
https://stackoverflow.com/questions/74179733
复制相似问题