c - 从整数数组到文件的奇怪输出
问题描述
嗨,我正在编写一个生成随机整数的程序,将它们放在一个数组中并将它们保存到一个文件中。一切似乎都很好,但是在我打开这个文件后,它有这个奇怪的内容:^K^@^@^S^@^@^@^[^@ 我做错了什么?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
int tab[10];
int fd;
srand(time(0));
int i;
for(i = 0; i < 10; i++)
tab[i] = rand() % 50;
if(argc != 2 || strcmp(argv[1], "--help") == 0)
{
.......
}
fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644);
write(fd, tab, 10);
close(fd);
return 0;
}
解决方案
内容很奇怪,因为您正在编写二进制值,从 0 到 50 的随机字符代码。但是信息就在那里(好吧,您必须编写sizeof(int)
更多的数据来存储所有数据,并且它可能会损坏窗口,因为您不见了O_BINARY
,并且可能在某些位置插入了一些回车符...):
fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644); // add | O_BINARY if you use windows
write(fd, tab, 10 * sizeof(int)); // you can use (fd,tab,sizeof(tab)) too as it's an array, not a pointer
使用十六进制编辑器,您将看到值(有很多零,因为您的值可以以字节编码)。但不是用文本编辑器。
如果要将格式化的整数写入字符串,请在文本文件中的值上使用fopen
和,而不是二进制文件。fprintf
快速而肮脏(也未经测试:)):
FILE *f = fopen(argv[1], "w"); // #include <stdio.h> for this
if (f != NULL)
{
int i;
for (i = 0; i < 10; i++)
{
fprintf(f,"%d ",tab[i]);
}
fclose(f);
}
推荐阅读
- javascript - Netlify Forms Nuxt JS 错误 - POST https://festive-fermi-f2a8f1.netlify.app/ 404。未捕获(承诺)错误:请求失败,状态码 404
- api - 我在使用 Youtube RATE API 时遇到问题
- django - Django 迁移修改继承的默认值
- http - 无法读取整个响应正文
- php - 缺少身份验证中间件的经过身份验证的用户的功能测试
- database - 如何将数据库从服务器复制到本地主机
- laravel - CARBON 使用工作日数获取日期范围之间的所有日期
- python - 如何创建 2 个相同的对象列表以及如何让操作同时影响两个列表?
- javascript - 尝试使用节点加密/密码加密文件时密钥长度无效
- bash - 我对 BASH 脚本非常陌生,如何在文件中保留关键字命中 (grep) 的运行总数(计数),然后最后显示总数?