PHP

fread在实际项目中的综合应用案例

小樊
84
2024-08-27 16:32:20
栏目: 编程语言

fread 是一个用于从文件中读取数据的函数,它通常用于二进制文件的读取

  1. 读取图像文件:
#include<stdio.h>

int main() {
    FILE *file;
    file = fopen("image.jpg", "rb");
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char *buffer = (unsigned char *)malloc(fileSize + 1);
    if (buffer == NULL) {
        printf("内存分配失败\n");
        return 1;
    }

    size_t result = fread(buffer, 1, fileSize, file);
    if (result != fileSize) {
        printf("读取错误\n");
        return 1;
    }

    // 处理图像数据(例如,显示图像)

    free(buffer);
    fclose(file);
    return 0;
}
  1. 读取音频文件:
#include<stdio.h>

int main() {
    FILE *file;
    file = fopen("audio.wav", "rb");
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char *buffer = (unsigned char *)malloc(fileSize + 1);
    if (buffer == NULL) {
        printf("内存分配失败\n");
        return 1;
    }

    size_t result = fread(buffer, 1, fileSize, file);
    if (result != fileSize) {
        printf("读取错误\n");
        return 1;
    }

    // 处理音频数据(例如,播放音频)

    free(buffer);
    fclose(file);
    return 0;
}
  1. 读取配置文件:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>

typedef struct {
    char key[100];
    char value[100];
} ConfigItem;

ConfigItem *readConfigFile(const char *filename, int *itemCount) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        return NULL;
    }

    *itemCount = 0;
    ConfigItem *configItems = NULL;
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        char *equalSign = strchr(line, '=');
        if (equalSign == NULL) {
            continue;
        }

        ConfigItem *newConfigItems = (ConfigItem *)realloc(configItems, (*itemCount + 1) * sizeof(ConfigItem));
        if (newConfigItems == NULL) {
            printf("内存分配失败\n");
            free(configItems);
            return NULL;
        }
        configItems = newConfigItems;

        ConfigItem *item = &configItems[*itemCount];
        strncpy(item->key, line, equalSign - line);
        item->key[equalSign - line] = '\0';
        strcpy(item->value, equalSign + 1);
        item->value[strlen(item->value) - 1] = '\0'; // 去除换行符

        (*itemCount)++;
    }

    fclose(file);
    return configItems;
}

int main() {
    int itemCount;
    ConfigItem *configItems = readConfigFile("config.txt", &itemCount);
    if (configItems == NULL) {
        return 1;
    }

    for (int i = 0; i< itemCount; i++) {
        printf("%s: %s\n", configItems[i].key, configItems[i].value);
    }

    free(configItems);
    return 0;
}

这些示例展示了如何使用 fread 函数在实际项目中处理不同类型的文件。请注意,这些示例仅用于演示目的,实际项目中可能需要更复杂的错误处理和功能实现。

0
看了该问题的人还看了