トップ «前の日記(2010/06/05(Sat)) 最新 次の日記(2010/06/07(Mon))»
【ソース+水=麦茶色の何か】

半期 四半期 全カテゴリ

今日の一言


2010/06/06(Sun) るいぱんこ [長年日記] 0:00現在 21℃

_ [C++][Debian][FC][Ubuntu][Linux][研究関係][雑記] C言語(C++)でlsを行う

こんな感じで書く。

 #include <stdio.h>
 #include <stdlib.h>
 #include <dirent.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 int main( int argc, char **argv )
 {
   char *pass;
   DIR *dp;
   struct dirent *entry;
   struct stat statbuf;

   if(argc<2)
   { pass = getenv("PWD");}
   else
   { pass = argv[1];}

   if(( dp = opendir(pass) ) == NULL )
   {
     perror("opendir_error!");
     exit( EXIT_FAILURE );
   }

   while((entry = readdir(dp)) != NULL)
   {
     stat(entry->d_name, &statbuf);
     if(S_ISDIR(statbuf.st_mode))  //ディレクトリの場合
     {
       printf("%s/\n", entry->d_name);
     }
     else  //それ以外の場合
     {
       printf("%s\n", entry->d_name);
     }
   }
   closedir(dp);
   return(0);
 }

基本的にはファイルストリームっぽいものと思えば良さそう。

参考:

http://www.geocities.co.jp/SiliconValley-Cupertino/4084/Cprogram/myls.html

http://www5a.biglobe.ne.jp/~nkgwtty/njaLinuxC_Lang01.html

http://www.c-lang.net/stat/

*環境依存だけど、stat関数はかなり便利。もう少し試してみようとおもう。

_ [C++][Debian][FC][Ubuntu][Linux][研究関係][雑記] C言語(C++)でmkdirを行う・改

既にファイルが存在していた場合のエラーメッセージを追加。

 #include <sys/types.h>
 #include <sys/stat.h>
 #include <dirent.h>
 #include <stdio.h>
 int main()
 {
   DIR *dp;
   mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
   if ( mkdir("./newdir", mode) != 0 )
   {
     if ( (dp = opendir("./newdir")) != NULL )
       printf("target dir exists!\n");
     else
       printf("mkdir error!\n");
   }
 }

もっと真面目にエラー処理したい場合は、「errno.h」をインクルードして、グローバル変数「errno」でエラー分けすればいい。(表示はstrerror()とかで)

参考: http://www5a.biglobe.ne.jp/~nkgwtty/njaLinuxC_Lang01.html

_ [C++][Debian][FC][Ubuntu][Linux][研究関係][雑記] C言語(C++)でディレクトリ内に、ある名前を持ったファイルが存在するかを確認する

こんな感じで書く。

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <dirent.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 int main( int argc, char **argv )
 {
   char *pass;
   char *target;
  DIR *dp;
  struct dirent *entry;
  struct stat statbuf;
  if(argc<3)
  {
    printf("missing file operand!\n");
    printf("ex:  %s Pass Target\n", argv[0] );
    return -1;
  }
  else
  {
    pass = argv[1];
    target = argv[2];
  }
  if(( dp = opendir(pass) ) == NULL )
  {
	  perror("opendir_error!");
	  exit( EXIT_FAILURE );
  }
  while((entry = readdir(dp)) != NULL)
  {
	  if (strcmp(target,entry->d_name) == 0)
	  {
         printf("\"%s\" found in \"%s\"\n",target, pass);
         return 0;
     }
  }
  printf("\"%s\" NOT found in \"%s\"\n",target, pass);
  closedir(dp);
  return(0);
 }

ファイルの新規作成を行う際に、間違って上書きしてしまうのを防ぐのに応用できると思われ。

*処理速度とかは無視。適当に書いただけなので。