c - 将int写入c中的文件: getting weird character "\00"

标签 c int

我想使用函数 write 将一些 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”时,我得到了这个: enter image description here 这是我如何初始化数组 **time

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);
        }
    }

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

最佳答案

这一行是错误的:

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

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

所以这是正确的:

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

但无论如何,使用 fopen 代替 openfprintf 代替 sprintf 后跟

valgrind 输出与此问题无关。

关于c - 将int写入c中的文件: getting weird character "\00",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935938/

相关文章:

Java:找不到适合 Scanner(int) 的构造函数

c# - 合并 2 个整数的文本而不是将它们加在一起

python - 双端队列扩展时将字节更改为整数

java - 如何在数学方程中使用字符串变量名称?

c++ - VC++中Float数据类型的值,如何判断是否混合了字符串或特殊字符

c - 维基百科关于内存泄漏的文章中的错误

c++ - 在寻找用于回车删除的有效 C 和 C++ 方法时感到茫然(阅读 .csv 文件)

c - 我有一个包含成员变量名称的字符串。我想用它来访问成员本身

c++ - 从结构中形成 16 位字

c# - 当可能为空字符串值时,将字符串数组值转换为 int