c - Windows 中的 UNIX 系统调用 'read' 和 'write'

标签 c windows unix

<分区>

如下代码表示,“读取”系统调用在 Windows 中使用 C 语言无法正常工作似乎很奇怪。

#include <fcntl.h>
#include <windows.h>
#include <stdio.h>

int main()
{
    int fd = open("a.txt",O_RDONLY);
    char *buf = (char *)malloc(4);
    read(fd,buf,4);
    printf("the string is %s\n",buf);
    return 0;
}

非常简洁的c代码,a.txt的内容就是'abcd'。但是当我在 Windows 中运行这段代码时(env 是 MinGW,编译器是 gcc)。输出是

abcd?

什么是字符“?”在这个输出字符串中?

我可以在 Windows 中使用“读取”或“写入”unix 系统调用吗?

提前致谢。

最佳答案

此问题与平台或操作系统无关。这只是因为您缺少字符串终止符

在 C 中,char 字符串实际上称为 null-terminated 字节字符串null-terminated 位很重要,因为所有将指向 char 的指针视为字符串的函数都会查找此终止符以了解字符串何时结束。

这意味着四个字符的字符串实际上需要 五个 的空间,最后一个是字符空终止符 '\0'

由于没有终止符,字符串函数可以而且将会越界寻找终止符,导致 undefined behavior .

所以:

char buf[5];  // 4 + 1 for terminator
int size = _read(fd, buf, 4);  // Windows and the MSVC compiler doesn't really have read

// _read (as well as the POSIX read) returns -1 on error, and 0 on end-of-file
if (size > 0)
{
    buf[size] = '\0';  // Terminate string
    printf("the string is %s\n", buf);
}

关于c - Windows 中的 UNIX 系统调用 'read' 和 'write',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48706138/

相关文章:

linux - shell脚本中的计数值

c - 出现错误 "assignment makes pointer from integer without a cast"

c# - 无法从 Windows 服务连接到 WCF 服务

c - 如何转义 C 的 printf 中的 %(百分号)符号

.net - 如何监控 .Net 应用程序的跟踪输出?

mysql - 在 Windows 上设置 MySQL 比在 Linux 上设置困难吗?

c - 如何检查二进制文件中的共享库版本

linux - 如何实际查找 UNIX 上进程的死锁原因?

c - 在 C 语言中总是变得真实

c++ - 用于为 C/C++/脚本代码着色的优秀 WordPress 扩展是什么?