スニぺったん

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

  • C言語
  • パスのファイルが存在するか調べる関数 (file_is_exists)

パスのファイルが存在するか調べる関数 (file_is_exists)

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

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

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

#ifdef _WIN32
#include <windows.h>
#endif

/**
 * file_pathのファイルが存在するならtrueを返し、存在しないならfalseを返す。
 */
bool
file_is_exists(const char *file_path) {
    if (!file_path) {
        return false;
    }

    // パスの末尾のスラッシュを除去。
    size_t len = strlen(file_path);
    char *path = malloc(len+1);
    if (!path) {
        return false;
    }
    strcpy(path, file_path);
    if (len && (path[len-1] == '/' || path[len-1] == '\\')) {
        path[len-1] = '\0';
    }

#ifdef _WIN32
    // pathをワイド文字列に変更。日本語のパスに対応するため。
    size_t buf_len = MultiByteToWideChar(CP_ACP, 0, path, -1, NULL, 0);
    if (buf_len == 0) {
        free(path);
        return false;
    }

    wchar_t *wpath = calloc(buf_len+1, sizeof(wchar_t));
    if (!wpath) {
        free(path);
        return false;
    }

    if (MultiByteToWideChar(CP_ACP, 0, path, -1, wpath, buf_len) == 0) {
        free(path);
        free(wpath);
        return false;
    }

    struct _stat s;
    int res = _wstat(wpath, &s);
    free(path);
    free(wpath);
#else
    struct stat s;
    int res = stat(path, &s);
    free(path);
#endif

    if (res == -1) {
        return false;
    }

    return true;
}

int
main(int argc, char *argv[]) {
    assert(file_is_exists(NULL) == false);
    assert(file_is_exists("nothing") == false);

    if (argc >= 2) {
        bool b = file_is_exists(argv[1]);
        printf("%d\n", b);
        return 0;
    }

    return 0;
}