首页 > 解决方案 > 从整数数组到文件的奇怪输出

问题描述

嗨,我正在编写一个生成随机整数的程序,将它们放在一个数组中并将它们保存到一个文件中。一切似乎都很好,但是在我打开这个文件后,它有这个奇怪的内容:^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;
}

标签: csystem-calls

解决方案


内容很奇怪,因为您正在编写二进制值,从 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);
}

推荐阅读