C语言文件读写工具类

发一个自己写的文件读写工具类。

FileUtil.h

//
// Created by gj21798 on 2018/6/11.
//

#ifndef CBASIC_FILEUTIL_H
#define CBASIC_FILEUTIL_H

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

bool isFileExists(const char *filename);

unsigned int getFileSize(const char *filename);

int loadIntoBuffer(const char *filename, char** out, unsigned int len);

void printBufferWithHex(const unsigned char *buf, unsigned int len);

#endif //CBASIC_FILEUTIL_H

FileUtil.c

//
// Created by gj21798 on 2018/6/11.
//

#include "FileUtil.h"

#define BUF_SIZE 1024

bool isFileExists(const char *filename)
{
    return access(filename, F_OK) != -1;
}

unsigned int getFileSize(const char *filename)
{
    struct stat stat_buf;
    stat(filename, &stat_buf);
    unsigned int len = (unsigned int) stat_buf.st_size;
    return len;
}

int loadIntoBuffer(const char *filename, char** out, unsigned int len)
{
    FILE *file;
    file = fopen(filename, "r");
    if (file == NULL)
    {
        return 0;
    }

    int total = 0;
    size_t rc = 0;
    while ((rc = fread(*out + total, 4, BUF_SIZE, file)) != 0)
    {
        total += rc;
    }

    fclose(file);
    return 1;
}

void printBufferWithHex(const unsigned char *buf, unsigned int len)
{
    if (len <= 0)
    {
        return;
    }

    for (int i = 0; i < len; i++)
    {
        if (i % 0x10 == 0)
        {
            printf("
0x%p ", buf + i);
        }
        printf("%02X ", *(buf + i));
    }
    printf("
");
}
View Code

写个小程序测试一下:

#include "FileUtil.h"

int main(int argc, char **argv)
{
    char *filename = "D:\CTest\main.c";
    unsigned int len = 0;
    char* pBuf;

    if(!isFileExists(filename))
    {
        fprintf(stderr, "file %s not exists.", filename);
        return -1;
    }

    if((len=getFileSize(filename)) == 0)
    {
        fprintf(stderr, "file %s is empty.", filename);
        return 0;
    }

    pBuf = (char *) calloc(1, len+1);
    if (pBuf == NULL)
    {
        fprintf(stderr, "alloc memory failed.");
        return -1;
    }

    if(!loadIntoBuffer(filename, &pBuf, len))
    {
        fprintf(stderr, "load file %s into memory failed.", filename);
        return -1;
    }

    printBufferWithHex(pBuf, len);

    free(pBuf);

    return 0;
}

程序运行截图:

原文地址:https://www.cnblogs.com/areful/p/11324844.html