3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ファイルの存在チェック

Last updated at Posted at 2014-10-08

簡易的なファイルの存在チェック

Linux GNU C(glibc)

Linuxのファイル名はディレクトリが持っているためディレクトリの内容を調べる。

diropen() して 帰ってくる ディレクトリ・ストリームを readdir() に投げる。
dirent 構造体のメンバにiノード番号などの情報も入っているが、
メンバ変数 d_name を調べればいけるようだ。

注:ほとんどメモ書き。実用はキビシイ。

char d_name[256]


# include <stdio.h>
# include <errno.h>
# include <sys/types.h>
# include <dirent.h>

enum { SUCCESS };

int main()
{
	DIR *d = opendir("dir_name");
	struct dirent *dp;

	switch(errno) {
		case EACCES :
			fprintf(stderr, "Permission Denied\n");
			return errno;
		case ENOTDIR :
			fprintf(stderr, "Not a Directory\n");
			return errno;
		case SUCCESS:
			break;
	}
	char name[] = "file_name";

	while( (dp = readdir(d)) != NULL) {
		if(*(dp->d_name) == *file_name) {
			printf("file already exist\n");
		}
	}
	return 0;
}

追記
errnoに対応するメッセージを出力する関数にperror関数があったので
こっちでエラーメッセージは吐いた方がよかった。


void perror(const char* s)

引数sがヌルポインタ、空文字列ではない場合、
errornoに対応するメッセージ *s を出力。

3
3
1

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?