【问题标题】:Write int into file in c : getting weird character "\00"将 int 写入 c 中的文件:得到奇怪的字符“\00”
【发布时间】:2018-04-20 07:05:50
【问题描述】:

我想使用函数 write 将一些 int 写入二进制文件。我的整数在两个“数组”中,我想将每个 int 写入我的文件。我的代码:

void write_graph(int **time, int **tailles, int lenght, int thread_number) //lenth = nombre de tests pour un nombre de coeur
{
    int f, i, j;
    char tmp[16] = {0x0};
    f = open("val", O_CREAT | O_RDWR | O_TRUNC, 0666);
    if (f < 0)
    {
        perror("open in write_graph");
        return; 
    }
    else
    {
        for (j = 0; j < lenght; j++)
        {
            for (i = 0; i < thread_number; i++)
            {
                int ti = time[i][j];
                int tl = tailles[i][j];
                printf("%d %d",ti, tl);
                //sprintf(tmp, "%d %d", ti, tl);
                sprintf(tmp, "%d", ti);
                write(f, tmp, sizeof(tmp));
            }
            write(f, "\n", 1);
        }
    }
}

通常,我也会从 **tailles 中写入整数,但它包含随机数,我对此没有任何错误(我简化了一些代码)。在我的 for 循环中,我有一个 printf。它很好地显示了我的整数。但是当我打开我的文件“val”时,我得到了这个: 这是我如何初始化我的数组**时间

time = malloc(thread_number * sizeof(int *));
    tailles = malloc(thread_number * sizeof(int *));
    for (i = 0; i < thread_number; i++)
    {
        time[i] = malloc(lenght * sizeof(int));
        tailles[i] = malloc(lenght * sizeof(int));
    }

    for (i = 0; i < thread_number; i++)
    {
        for (j = 0; j < lenght; j++)
        {
            time[i][j] = j;
            tailles[i][j] = Random(1, 10);
        }
    }

我尝试了很多不同的技术,但我仍然得到相同的结果...我不知道如何将 int 写入 c 中的文件... 这是 valgrind 显示的内容(我不知道如何解释泄漏摘要):

【问题讨论】:

  • 为什么这被标记为“二进制文件”?您正在尝试编写文本文件。请删除标签或澄清。

标签: c int


【解决方案1】:

这一行是错误的:

write(f, tmp, sizeof(tmp));

无论字符串的实际长度如何,您总是写入sizeof(tmp) (= 16) 个字节。字符串的长度为strlen(tmp)

所以这是正确的:

write(f, tmp, strlen(tmp));

但无论如何,使用fopen 代替openfprintf 代替sprintf 后跟write 更容易。

valgrind 输出与此问题无关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    相关资源
    最近更新 更多