Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3271
  • 博文数量: 1
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 21
  • 用 户 组: 普通用户
  • 注册时间: 2015-01-20 18:11
文章分类

全部博文(1)

文章存档

2015年(1)

我的朋友
最近访客

分类: C/C++

2015-01-20 18:28:10

这里面(buff[strlen(buff)-1]=='/')检测的比较好

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include<dirent.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>

  8. int main (int argc, char *argv[])
  9. {
  10.     if(2 != argc)
  11.     {
  12.         printf("\n Please pass in the directory name \n");
  13.         return 1;
  14.     }

  15.     DIR *dp = NULL;
  16.     struct dirent *dptr = NULL;
  17.     // Buffer for storing the directory path
  18.     char buff[128];
  19.     memset(buff,0,sizeof(buff));

  20.     //copy the path set by the user
  21.     strcpy(buff,argv[1]);

  22.     // Open the directory stream
  23.     if(NULL == (dp = opendir(argv[1])) )
  24.     {
  25.         printf("\n Cannot open Input directory [%s]\n",argv[1]);
  26.         exit(1);
  27.     }
  28.     else
  29.     {
  30.         // Check if user supplied '/' at the end of directory name.
  31.         // Based on it create a buffer containing path to new directory name 'newDir'
  32.         if(buff[strlen(buff)-1]=='/')
  33.         {
  34.             strncpy(buff+strlen(buff),"newDir/",7);
  35.         }
  36.         else
  37.         {
  38.             strncpy(buff+strlen(buff),"/newDir/",8);
  39.         }

  40.         printf("\n Creating a new directory [%s]\n",buff);
  41.         // create a new directory
  42.         mkdir(buff,S_IRWXU|S_IRWXG|S_IRWXO);
  43.         printf("\n The contents of directory [%s] are as follows \n",argv[1]);
  44.         // Read the directory contents
  45.         while(NULL != (dptr = readdir(dp)) )
  46.         {
  47.             printf(" [%s] ",dptr->d_name);
  48.         }
  49.         // Close the directory stream
  50.         closedir(dp);
  51.         // Remove the new directory created by us
  52.         rmdir(buff);
  53.         printf("\n");
  54.     }

  55.     return 0;
  56. }
下面这段是拷贝man page的。

点击(此处)折叠或打开

  1. #define _SVID_SOURCE
  2. /* print files in current directory in reverse order */
  3.        #include <dirent.h>

  4.        int
  5.        main(void)
  6.        {
  7.            struct dirent **namelist;
  8.            int n;

  9.            n = scandir(".", &namelist, NULL, alphasort);
  10.            if (n < 0)
  11.                perror("scandir");
  12.            else {
  13.                while (n--) {
  14.                    printf("%s\n", namelist[n]->d_name);
  15.                    free(namelist[n]);
  16.                }
  17.                free(namelist);
  18.            }
  19.        }



阅读(308) | 评论(0) | 转发(0) |
1

上一篇:没有了

下一篇:没有了

给主人留下些什么吧!~~