作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
int i, stream;
for (i = 20; i < 40; i++) {
if (i % 2 == 0) {
stream = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
char *x;
*x = i;
write(stream, &x, 1024);
close(stream);
}
}
return 0;
}
我在文件中得到如下字符:
@^@^@^@^@Z^@^@2@^@^@
最佳答案
代码中存在多个问题。
一个
char *x;
*x = i;
这将创建一个不指向任何地方的指针,并立即通过该指针进行写入。未定义的行为。您可能想要这个:
char x = i;
两个
write(stream, &x, 1024);
这将从变量x
的地址开始写入1024个字节。在原始情况下,x
是一个指针,因此它很可能占用 4 或 8 个字节(分别取决于您的系统是 32 位还是 64 位)。通过我上面建议的更改,x
是一个单字节变量。
无论哪种情况,都没有 1024 字节的数据可供写入。您的意思可能是:
int main(int argc, char* argv[]) {
int i, stream;
for (i = 20; i < 40; i++) {
if (i % 2 == 0) {
stream = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
char x = i;
write(stream, &x, 1);
close(stream);
}
}
return 0;
}
关于c - 我的文件中出现了奇怪的字符。我在C语言中使用无缓冲I/O流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57006948/
我是一名优秀的程序员,十分优秀!