我想使用函数 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”时,我得到了这个: 这是我如何初始化数组 **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 显示的内容(我不知道如何解释泄漏摘要):
最佳答案
这一行是错误的:
write(f, tmp, sizeof(tmp));
无论字符串的实际长度如何,您总是写入 sizeof(tmp)
(= 16) 个字节。字符串的长度为 strlen(tmp)
:
所以这是正确的:
write(f, tmp, strlen(tmp));
但无论如何,使用 fopen
代替 open
和 fprintf
代替 sprintf
后跟 写
。
valgrind 输出与此问题无关。
关于c - 将int写入c中的文件: getting weird character "\00",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935938/