fread
是一個用于從文件中讀取數據的函數,它通常用于二進制文件的讀取
#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;
}
#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;
}
#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
函數在實際項目中處理不同類型的文件。請注意,這些示例僅用于演示目的,實際項目中可能需要更復雜的錯誤處理和功能實現。