我有下面的代码,它将 buf[12] 中的“hello world”复制到文件 foo.txt 中,并且确实如此。
我的问题是:
buf[12] 中只有 12 个字符(包括 ' ' 终止符),'write' 函数不应该只将 12 个字符复制到文件中吗?为什么文件中写入了 100 个字节? (我认为“写入”函数应该只将 MOST MAXLINE 字节复制到文件中。)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define MAXLINE 100
int main() {
char buf[12] = "hello world";
int fd, writtenbytes;
fd=open("foo.txt", O_RDWR, 0);
if(fd == -1) {
perror("Error opening file");
exit(1);
}
if ((writtenbytes = write(fd, buf, MAXLINE)) < 0 ) {
perror("writing");
}
printf("writtenbytes: %d\n", writtenbytes);
}
输出:
writtenbytes: 100
简短回答(为什么你的文件是 100 字节):
#define MAXLINE 100
...
if ((writtenbytes = write(fd, buf, MAXLINE)) < 0 ) {
perror("writing");
}
您的代码表示将 100 个字节写入文件中。
你的问题基本上是“为什么没有错误,因为我的数组只有 12 个字节”?
嗯,您的代码存在缺陷,尝试从 12 字节缓冲区写入 100 字节。这是代码中的错误,它将调用未定义的行为。
有时未定义的行为会生成运行时错误,例如分段错误。有时它会按预期工作。有时你的鼻子里可能会召唤出恶魔。
您的数组
buf
在堆栈上分配,并且那里可能有足够的可用空间。所以你不会遇到SegFault。您只需在文件中写入一堆随机垃圾即可。
对于这种效果可能有一个现有的答案,在这种情况下,标记为 dup。