我有以下代码:
#include <stdio.h>
#include <unistd.h>
int main () {
int fd = open("filename.dat", O_CREAT|O_WRONLY|O_TRUNC, 0600);
int result = write(fd, "abcdefghijklmnopqrstuvxz", 100);
printf("\n\nfd = %d, result = %d, errno = %d", fd, result, errno);
close(fd);
return 0;
}
我试图了解当我尝试向文件写入比可用字节更多的字节时会发生什么。所以我调用 write
并要求程序写入 100 个字节,而我的字节数远少于此。结果:stdout
中的一堆内容最终出现在 filename.dat
中。如果我使用 strlen("abcdefghijklmnopqrstuvxz")
而不是 100
,我会得到想要的结果。那么我的问题是:为什么程序试图在我的字符串中写入超过 '\0'
字符的内容?这里是否发生了一些未定义的行为?
最佳答案
My question then is: why is the program trying to write beyond the '\0' character on my string?
函数write(2)
不关心 0 终止符。它实际上根本不关心缓冲区内容:它会尝试写入您告诉它的字节数。
Is there some undefined behavior going on here
当然,尝试写的比你写的多可能会招致操作系统的愤怒,如果它触及不可访问的内存,操作系统可能会决定终止你的进程。
关于c - 写入文件会在我想要的内容之上写入垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12236445/