c - C中文件获取内容

标签 c file-io character-arrays

将文件内容放入单个字符数组的最佳方法是什么?

我已阅读此问题:

Easiest way to get file's contents in C

但从评论中,我发现该解决方案不适用于大文件。我确实可以访问 stat 函数。如果文件大小超过 4 GB,我应该返回错误吗?

文件的内容是加密的,并且由于它是由用户提供的,因此它可以是任何人想要的大小。我希望它在文件太大时返回错误并且不会崩溃。使用文件内容填充字符数组的主要目的是将其与另一个字符数组进行比较,并且(如果需要并配置为这样做)将这两者记录到一个日志文件(或多个日志文件,如果需要) )。

最佳答案

您可以使用 sys/stat.h 中的 fstat(3)。这里有一个小函数来获取文件的大小,如果文件小于 4GB,则分配内存,否则返回 (-1)。它将文件读取到传递给 char *buffer 的 char * 数组,其中包含整个文件的内容。使用后应将其释放。

#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

char *loadlfile(const char *path)
{
    int file_descr;
    FILE *fp;
    struct stat buf;
    char *p, *buffer;

    fstat((file_descr = open(path, O_RDONLY)), &buf);

// This check is done at preprocessing and requires no check at runtime.
// It basically means "If this machine is not of a popular 64bit architecture,
// it's probably not 128bit and possibly has limits in maximum memory size.
// This check is done for the sake of omission of malloc(3)'s unnecessary
// invocation at runtime.

//    Amd 64               Arm64                      Intel 64       Intel 64 for Microsofts compiler.
#if !defined(__IA_64) || !defined(__aarch64__) || !defined(__ia64__) || !defined(_M_IA64)
#define FILE_MAX_BYTES (4000000000)
    // buf.st_size is of off_t, you may need to cast it.
    if(buf.st_size >= FILE_MAX_BYTES-1)
        return (-1);
#endif

    if(NULL == (buffer = malloc(buf.st_size + 1)))
        return NULL;

    fp = fdopen(file_descr, "rb");

    p = buffer;
    while((*p++ = fgetc(fp)) != EOF)
        ;
    *p = '\0';

    fclose(fp);
    close(file_descr);
    return buffer;
}

可以找到用于各种事物的非常广泛的预定义宏列表@ http://sourceforge.net/p/predef/wiki/Home/ 。进行体系结构和文件大小检查的原因是,malloc 有时可能会很昂贵,因此最好在不需要时忽略/跳过它的使用。并查询最大内存。 4GB 对于一整 block 4GB 存储来说只是浪费这些宝贵的周期。

关于c - C中文件获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14146074/

相关文章:

c - 如何在我的源代码或系统库中获取一个函数的 cpu 周期和执行时间

c++ - RegLoadKey 给出错误代码 5(拒绝访问)

C++:自定义对象序列化/反序列化失败

c# - FileNotFoundException 从 Windows 应用商店应用程序的 Assets 文件夹中读取 JSON 文件

c++ - 递归函数循环遍历字符数组

串行数据与填充数据的缓存性能

iphone - long double 的格式说明符(我想截断小数点后的 0)

c++ - 覆盖映射文件中间数据的有效方法

java - 如何返回多个值

java - 数组和字符串