首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在unistd.h中使用write()和read()

如何在unistd.h中使用write()和read()
EN

Stack Overflow用户
提问于 2022-10-24 10:25:10
回答 1查看 73关注 0票数 -1

我试图使用unistd.h中的read()write()函数,但是每当我尝试输入任何内容时,它都无法工作。我只能使用fcntl.h和unistd.h的函数,而不是stdio.h的函数。

这是我的代码:

代码语言:javascript
运行
复制
#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 
    }
}

问题是我没有得到我所提供的输入的期望输出。例如:

代码语言:javascript
运行
复制
//input 
Hello 

//output
Block read: 
<Hello> 
EN

回答 1

Stack Overflow用户

发布于 2022-10-28 21:17:21

我编写了如何使用read(2)write(2)的示例代码。我不知道你是否需要使用/dev/pts/。我从来没用过,现在也不用了。也许我的例子会有帮助。

string.h只包含在strlen(3)中。

代码语言:javascript
运行
复制
#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)返回值的注释,还删除了检查它,因为它似乎没有必要。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74179733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档