スニぺったん

無料のコードスニペットを掲載しています。言語ごとにコードスニペットを検索し、利用することが可能です。コードのライセンスはトップページをご覧ください。

  • C言語
  • ファイル内容の読み込み (read_file)

ファイル内容の読み込み (read_file)

総合評価: - 作成日: 2025-10-04

コメント:
Linuxでメモリリークチェック済み。
Windows/Linuxで動作確認済み。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char *
read_file(const char *path) {
    if (!path) {
        return NULL;
    }

    FILE *fp = fopen(path, "r");
    if (!fp) {
        return NULL;
    }

    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char *s = malloc(size+1);
    if (!s) {
        fclose(fp);
        return NULL;
    }

    fread(s, sizeof(s[0]), size, fp);
    s[size] = 0;

    fclose(fp);

    return s;
}

int
main(int argc, char *argv[]) {
    if (argc < 2) {
        return 1;
    }

    char *content = read_file(argv[1]);
    if (!content) {
        return 1;
    }
    
    printf("%s\n", content);
    free(content);

    assert(read_file(NULL) == NULL);
    assert(read_file("nothing") == NULL);
    
    return 0;
}