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

如何用C语言将含二进制数据成员的结构体写入文件(附示例代码)

Writing a Struct with Binary Data to a File in C

Alright, let's break down how to write your struct binary (which includes both binary data and a string pointer) to a file correctly in C. First, let's fix a critical bug in your existing code that will cause undefined behavior right away:

Your bin.time_str is an uninitialized pointer. Calling sprintf on it will write to random memory, which will crash your program or cause corrupted data. You need to either allocate memory for it with malloc() or replace the pointer with a fixed-size character array (safer for struct serialization).


Step 1: Fix the time_str Member

Let's adjust the struct first to avoid pointer issues. A fixed-size array is simpler for file I/O:

// Revised struct with fixed-size string buffer (safer for serialization)
struct binary {
    char time_str[64];  // Enough space for your formatted time string
    uint16_t id;
    uint8_t data[8];
};

If you must use a pointer, you'll need to explicitly allocate memory before using sprintf:

struct binary bin;
bin.time_str = malloc(64);  // Allocate enough space
if (!bin.time_str) {
    perror("malloc failed");
    exit(EXIT_FAILURE);
}
// Use sprintf here, then free(bin.time_str) when done

Step 2: Write the Struct to a File

Since your struct contains binary data and (originally) a pointer, you have two reliable approaches:

Directly writing the struct with fwrite(&bin, sizeof(struct binary), 1, fp) works only if the struct is a POD (Plain Old Data) type. If your struct has pointers, this writes the pointer's memory address (not the actual string data), which is useless when reading the file later.

Instead, serialize each member explicitly:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <sys/time.h>
#include <string.h>
#include <arpa/inet.h>

struct binary {
    char time_str[64];
    uint16_t id;
    uint8_t data[8];
};

// Function to write the struct to a file
int write_binary_struct(FILE *fp, const struct binary *bin) {
    // Write the time string length (to know how much to read later)
    size_t str_len = strlen(bin->time_str) + 1;  // Include null terminator
    if (fwrite(&str_len, sizeof(size_t), 1, fp) != 1) return -1;
    if (fwrite(bin->time_str, str_len, 1, fp) != 1) return -1;

    // Write the uint16_t id (convert to network byte order for cross-platform compatibility)
    uint16_t be_id = htons(bin->id);
    if (fwrite(&be_id, sizeof(uint16_t), 1, fp) != 1) return -1;

    // Write the 8-byte binary data
    if (fwrite(bin->data, sizeof(uint8_t), 8, fp) != 8) return -1;

    return 0;
}

// Example usage
int main() {
    FILE *fp = fopen("binary_data.bin", "wb");  // Use "wb" for binary mode!
    if (!fp) {
        perror("fopen failed");
        return EXIT_FAILURE;
    }

    struct binary bin;
    // Populate the struct first
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    sprintf(bin.time_str, "%02d.%02d.%02d %02d:%02d:%02d", 
            tm->tm_mday, tm->tm_mon + 1, (tm->tm_year % 100),
            tm->tm_hour, tm->tm_min, tm->tm_sec);
    bin.id = 0x1234;
    for (int i = 0; i < 8; i++) {
        bin.data[i] = i;  // Sample binary data
    }

    if (write_binary_struct(fp, &bin) != 0) {
        perror("write failed");
        fclose(fp);
        return EXIT_FAILURE;
    }

    fclose(fp);
    return EXIT_SUCCESS;
}

Approach 2: Write the Entire POD Struct (Simpler, No Pointers)

If you're using the fixed-size time_str array (making the struct a POD type), you can write the entire struct in one go. Just remember to open the file in binary mode and handle endianness if you plan to read the file on a different system:

// Write the entire POD struct
if (fwrite(&bin, sizeof(struct binary), 1, fp) != 1) {
    perror("fwrite failed");
    fclose(fp);
    return EXIT_FAILURE;
}

⚠️ Note: This works only if all struct members are POD types (no pointers, no complex objects). Also, byte order (endianness) will differ between systems, so use htons()/ntohs() for integer types if cross-platform compatibility is needed.


Key Notes

  • Always open files in binary mode ("wb" for writing, "rb" for reading) to avoid unwanted newline conversions on Windows.
  • Check the return value of every fwrite call to ensure all data was written successfully.
  • If using pointers in your struct, you must serialize the actual data (not the pointer address) and track lengths so you can correctly read it back later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:31:36