linux路径文件名c,Linux下显示某一目录下文件名列表的C程序

以下是一个Linux/Unix下显示某一目录下文件列表的C程序,相当于最基本的ls命令的功能,显示的内容报告该目录下的子目录以及文件名:

1.#include

2.#include

3.#include

4.#include

5.int main(int argc,char *argv[])

6.{

7. DIR *dp;

8. struct dirent *dirp;

9. int n=0;

10. if (argc!=2)

11. {

12. printf("a single argument is required\n");

13. exit(0);

14. }

15. if((dp=opendir(argv[1]))==NULL)

16. printf("can't open %s",argv[1]);

17. while (((dirp=readdir(dp))!=NULL) && (n<=50))

18. {

19. if (n % 1 == 0) printf("\n");

20. n++;

21. printf("%10s ",dirp->d_name);

22. }

23. printf("\n");

24. closedir(dp);

25. exit(0);

26.}

如果只是显示该目录下的子目录名,则需要使用如下程序(其中还包括了一个对于子目录名的冒泡排序):

1.#include

2.#include

3.#include

4.#include

5.#include

6.

7.int main(int argc,char *argv[])

8.{

9. DIR *dp;

10. struct dirent *dirp;

11. struct stat buf;

12. char tempDirName[100];

13. char dirNames[100][100];

14. int n=0,i=0,j=0,dirCount=0;

15. if (argc!=2)

16. {

17. printf("a single argument is required\n");

18. exit(0);

19. }

20. strcat(tempDirName,argv[1]);//get the directory name

21. if((dp=opendir(argv[1]))==NULL)

22. printf("can't open %s",argv[1]);

23. while (((dirp=readdir(dp))!=NULL) && (n<=50))

24. {

25. //if (n % 1 == 0) printf("\n");

26. n++;

27. //printf("%10s ",dirp->d_name);

28. strcpy(tempDirName,"");//clear

29. strcat(tempDirName,argv[1]);//get the directory name

30. strcat(tempDirName,dirp->d_name);

31. if(IsDirectory(tempDirName))

32. {

33. //printf("\tDirectory!!!!");

34. strcpy(dirNames[dirCount],dirp->d_name);

35. //printf("\ttest:%s",dirNames[dirCount]);

36. dirCount++;

37. }

38. }

39. printf("\n");

40.

41. /* Sort */

42. for(j=0;j

43. {

44. for (i=0;i

45. if (strcmp( dirNames[i], dirNames[i+1])>0)

46. {

47. //printf("\nexchange %s and %s",dirNames[i], dirNames[i+1]);

48. strcpy(tempDirName,dirNames[i]);

49. strcpy(dirNames[i],dirNames[i+1]);

50. strcpy(dirNames[i+1],tempDirName);

51. }

52. }

53.

54. /* Output sorted list: */

55. for( i = 0; i < dirCount; ++i )

56. printf( "\n%s ", dirNames[i] );

57. printf( "\n" );

58.

59. closedir(dp);

60. exit(0);

61.}

62.

63.int IsDirectory(const char *dirname)

64.{

65. struct stat sDir;

66. if (stat(dirname,&sDir) < 0)

67. {

68. return 0;

69. }

70. if(S_IFDIR == (sDir.st_mode & S_IFMT))

71. {

72. return 1;

73. }

74. else

75. {

76. return 0;

77. }

78.}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值