注册 登录
编程论坛 Linux教室

ls显示隐藏文件

s308182454 发布于 2012-07-16 19:08, 1873 次点击
写了个实现ls功能的程序,听说设置参数可显示隐藏文件不过不知道怎么写,请高手帮个忙
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<dirnet>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<errno.h>
#define ERR_EXIT(n) (perror(n),exit(EXIT_FAILURE))
int main(void)
{  DIR *dir=opendir(".");
    struct dir *de;
    while((de=readdir(dir))!=NULL)
     {   if(strncmp(de->d_name,"."1)==0)
      contonue;
      printf("%s\n",de->d_name);
       }
closedir(dir);
exit(EXIT_SUCCESS);
return 0;


    }




}

3 回复
#2
pangding2012-07-16 21:35
你这程序未免错的地方也太多了吧,最起码头文件 dirent.h 你就没拼对。
你只要把那个 while 里的 if 去掉就可以显示隐藏文件了。(不过你调的那个函数显然写的不正确……)

简单的就是这样。如果你想要用选项控制你这个程序的行为,那么可以用 getopt() 来分析选项。我写了一个小例子,你可以参考。详细参考 man 3 getopt

程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
    int c, almost = 0;
    while ( (c = getopt(argc, argv, "a")) != -1) {
        switch(c) {
            case 'a': almost = 1; break;
            default: exit(EXIT_FAILURE); break;
        }
    }

    DIR *dir=opendir(".");
    struct dirent *de;

    while((de=readdir(dir)) != NULL) {
        if(!almost && strncmp(de->d_name,".", 1)==0)
            continue;
        printf("%s\n",de->d_name);
    }

    closedir(dir);
    exit(EXIT_SUCCESS);
}



[ 本帖最后由 pangding 于 2012-7-16 22:01 编辑 ]
#3
s9123601012012-09-13 09:28
大婶啊
#4
俺是你大爷2019-03-12 12:53
ls -a
1