简体   繁体   English

为什么write()不能正常工作?

[英]Why doesn't write() work properly?

int main() {
    int in = STDIN_FILENO;
    int out = STDOUT_FILENO;
    char word[100];
    int count;

    while ((count = read(in, word, 100)) != 0) {
        write(out, word, strlen(word));
        memset(word, 0, 255);
        count = read(in, word, 5);
    }
}

In the console I got 在控制台中,我得到了

hello world
hello world
hello stackoverflow
 stackoverflow
abcd
efgh
efgh

Why isn't this program echoing back exactly as it was written? 为什么该程序不完全按照编写的方式回显?

memset(word, 0, 255); is causing undefined behavior. 导致未定义的行为。 You are accessing index out of bounds for word. 您正在访问索引超出单词范围。 Also please note that as you are using strlen on word, you should always zero terminate as read does not do that. 另外请注意,由于您在单词上使用strlen ,因此应始终将零终止,因为read不会这样做。

You called count = read(in, word, 5); 你叫count = read(in, word, 5); in the end of the while loop. while循环的末尾。 That 5 bytes are dropped. 那5个字节被丢弃。 That's why the "hello" in "hello stackoverflow" and the "abcd\\n" in "abcd\\nefgh" are dropped. 这就是为什么删除"hello stackoverflow" "hello"中的"hello stackoverflow""abcd\\nefgh"中的"abcd\\n" "abcd\\nefgh"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM