【问题标题】:Issue while writting the data using write system call in linux在linux中使用write系统调用写入数据时出现问题
【发布时间】:2014-08-06 10:21:01
【问题描述】:

我已经编写了用于在 linux 中读取、写入系统调用的示例代码......执行没有任何问题。

因此,将缓冲区数据存储到文件中......

存储在文件中的预期结果是 Hello World!..但我正在像这样 Hello World 的文件中获取数据!^@

我需要做什么才能得到预期的结果?

int main(int argc , char *argv[])
{
        int fd;
        char buff[14];
        fd = open("myfile.txt",O_CREAT| O_WRONLY,0777);

        if(fd == -1)
        {
                printf("Failed to open the file to write");
                exit(0);
        }

        write(fd,"Hello World!\n",13);
        close(fd);

        fd = open("myfile.txt",O_RDONLY,0777);

        if(fd == -1)
        {
                printf("Failed to open the file to read");
                exit(0);
        }

        read(fd,buff,14);
        buff[14] = '\0';
        close(fd); 
        printf("Buff is %s\n",buff);

        return 0;
}

【问题讨论】:

  • buff[14] = '\0'; --> buff[13] = '\0';
  • 您是否进行了任何重新编译或重建?

标签: c linux linux-kernel operating-system


【解决方案1】:

您声明 buff 为 14 个字符,但您在位置 15 处写入终止符。这导致 两个 undefined behavior 实例:一个是因为您写入超出数组范围,一个是因为当您打印缓冲区时,您在位置 14 处有未初始化的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2016-05-01
    • 2020-09-21
    • 1970-01-01
    • 2013-05-21
    • 2011-02-14
    相关资源
    最近更新 更多