You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言使用write函数写入int到二进制文件出现"\00"异常字符问题

解决二进制文件写入二维int数组出现空字节的问题

你说用write()函数把两个二维int数组写入二进制文件后,出现了奇怪的\00字符(也就是空字节),先看你给出的代码片段,循环部分没写完,但我能大概梳理下可能的问题点和解决办法:

最可能的错误原因

你用的是int **类型的二维数组(指针数组),每个子数组是单独分配的内存块,写入时如果没处理好很容易出问题:

  1. 错误指定写入字节数:比如不小心把sizeof(int) * thread_number写成sizeof(int*),这会把指针的地址值(而非数组里的int数据)写入文件,指针的高位字节大概率是0,就会出现\00。
  2. 误写指针本身而非数据:如果代码里写的是write(f, &time[j], ...)而不是write(f, time[j], ...),写入的是指针变量的地址,同样会带来空字节。
  3. 未初始化的数组元素:如果二维数组里有没赋值的元素,内存里的随机值可能包含0,看起来像是“奇怪的字符”。

正确的写入代码示例

补全你没写完的循环,同时加上错误检查(避免写入失败没察觉):

void write_graph(int **time, int **tailles, int lenght, int thread_number) 
{
    int f, j;
    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++) {
            // 写入time[j]数组的全部thread_number个int
            ssize_t written = write(f, time[j], sizeof(int) * thread_number);
            if (written == -1) {
                perror("write time array failed");
                close(f);
                return;
            }
            if (written != sizeof(int) * thread_number) {
                fprintf(stderr, "Warning: only wrote %zd bytes for time[%d]\n", written, j);
            }
            // 写入tailles[j]数组的全部thread_number个int
            written = write(f, tailles[j], sizeof(int) * thread_number);
            if (written == -1) {
                perror("write tailles array failed");
                close(f);
                return;
            }
            if (written != sizeof(int) * thread_number) {
                fprintf(stderr, "Warning: only wrote %zd bytes for tailles[%d]\n", written, j);
            }
        }
        close(f);  // 记得关闭文件,避免数据未刷入磁盘
    }
}

调试小技巧

  • 先打印要写入的每个int值,确认业务数据里本身有没有0(如果是正常业务逻辑的0,那\00就是二进制的正常表示,不是错误)。
  • 用hexdump -C val(Linux/macOS)或者二进制编辑器打开生成的文件,对比内存中数组的字节和文件里的字节,定位空字节来源。
  • 检查write的返回值,确保每次都写入了预期的字节数,避免部分写入导致的异常。

内容的提问来源于stack exchange,提问作者Zul Huky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:19:28