LoginSignup
2
3

More than 5 years have passed since last update.

[C言語] 存在しないディレクトリをfopen()する

Last updated at Posted at 2018-02-13

はじめに

存在しないディレクトリのファイルをfopen()するときエラーになって詰まってしまった。
先にディレクトリを作成してからfopen()することで解決した。

ソースコード

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

...

FILE* fp;
char out_dir[256] = "";
char out_path[256] = argv[1];
char tmp[256];
char *tok;

// ディレクトリ名の取得
// fopen()では新規ディレクトリは作成されない(エラー)
strcpy(tmp, "/");
tok = strtok(tmp, "/");
while (tok) {
    char *c = tok;
    tok = strtok(NULL, "/");
    if (tok) {
        if (strlen(out_dir)) {
            sprintf(out_dir, "%s/%s", out_dir, c);
        } else {
            strcpy(out_dir, c);
        }
    } else {
        break;
    }
    // mkdir()は1階層までしか作成できない
    mkdir(out_dir, 0777); // 作成成功の場合は0が返る
}

if ((fp = fopen(out_path, "w")) == NULL) {
    fprintf(stderr, "file can not open %s\n", out_path);
    exit(EXIT_FAILURE);
}

fclose(fp);

...

最後に

pythonとかgoとかディレクトリがちゃんと扱える言語は偉大

2
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3