如下代码表示,“读取”系统调用在 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);
}