c - 我的文件中有奇怪的字符。我在 C 语言中使用无缓冲 I/O 流
问题描述
#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);
这将从变量的地址开始写入 1024 个字节x
。在原始情况下,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++ 中的 Linux 中以 wc 形式对非基于文本的文件进行字数计数的实现
- ios - 在 Mobilefirst V7.1 上使用 Clevertap 推送通知在启动画面上出现 iOS 应用程序崩溃问题
- java - 如何在 UIMA 中运行注释器
- listview - 如何在颤动中获取存储中存在的所有图像和视频。就像一个画廊应用程序
- angular - 获取持久数据到组件
- java - java中如何避免FileSystemNotFoundException
- linux - bash 和 awk 脚本以 YYYY-MM-DD 格式获取上个月的日期
- python - 在 Python 中从特定 DNS 服务器解析 IP
- c++ - 这个函数的参数?
- python - python - 如何将 arima 测试的结果输入到数据框中