ディレクトリ操作dirent.h - アールメカブ

アールメカブ


ディレクトリ操作dirent.h

Programming ここを参照

ディレクトリ名も取得する必要があれば,hidden_dir_h

#include<stdio.h>
#include<dirent.h>

void main(argc,argv)
	int argc;
	char*argv[];
{
	DIR *dir;
	struct dirent *dp;
	char path[512]; //  ディレクトリは引数から判断する.
	if(argc<=1){
		strcpy(path,".");
}
	else{
		strcpy(path,argv[1]);
	}
	
	if((dir=opendir(path))==NULL){
		perror("opendir");
   exit(-1);
	}
	
	for(dp=readdir(dir);dp!=NULL;dp=readdir(dir)){
		printf("%s\n",dp->d_name);// ディレクトリ名は表示しない
	}
	closedir(dir);
}

ほかにこんな情報

#include    <stdio.h>
#include    <dirent.h>

int main(argc,argv)
   int argc;
   char *argv[];
{
   DIR *dir;
   struct dirent *dp;
   
   char path[257];/*指定したディレクトリ名を入れる*/
   int f_count = 0;/*ファイル数カウント用*/
   char (*f)[33];/*ファイル名を保存する配列*/
   int i;/*↑の配列の添え字用*/
       
   if(argc!=2){
       printf("コマンドラインの入力形式が間違っています\n");
       printf("test_readdir02 入力ファイル名\n");
       exit(-1);
   }else{
       /*コマンドライン引数よりディレクトリ名を指定*/
       strcpy(path,argv[1]);
   }
   
   /*ディレクトリを開く*/
   if((dir=opendir(path))==NULL){
       perror("opendir");
       exit(-1);
   }
   /*ファイル数をカウントする*/
   while ((readdir(dir)) != NULL) {
       f_count++;
   }
   printf("f_count=%d\n",f_count); 

   /*★★★ここでポインタを先頭に★★★*/
    rewinddir(dir);

   /*ファイル名を入れる配列を確保する*/
   f = (char (*)[33])malloc((f_count-2) * 33);
   
   /*ファイル名を配列にコピーする*/
   i=0;
   for(dp=readdir(dir);dp!=NULL;dp=readdir(dir)){
       strcpy(f[i], dp->d_name);
       printf("%s\n",f[i]);
       i++;
   }
   closedir(dir);
   
   /*記憶域を開放*/
   free(f);
   
   return;
   
}
 
添付ファイル: filedir.c 714件 [詳細]
 
Link: Programming(4983d) Programming_C(5434d) hidden_dir_h(5789d)
Last-modified: 2008-08-19 (火) 10:16:02 (5727d)