
在C语言中读入整个文件数据的方法主要有:使用fopen和fread、使用fopen和fgets、使用mmap内存映射。其中,使用fopen和fread是最常用的方法,可以高效地读取文件内容。接下来,我们详细讨论这三种方法,并给出示例代码。
一、使用fopen和fread
概述
使用fopen打开文件,fread读取文件内容,最后用fclose关闭文件。这种方法适用于读取二进制文件和文本文件。
示例代码
#include <stdio.h>
#include <stdlib.h>
void read_file_fread(const char *filename) {
FILE *file = fopen(filename, "rb");
if (!file) {
perror("Failed to open file");
return;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
char *buffer = (char *)malloc(file_size + 1);
if (!buffer) {
perror("Failed to allocate memory");
fclose(file);
return;
}
fread(buffer, 1, file_size, file);
buffer[file_size] = '