๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ฒœ์ฒœํžˆ, ๊พธ์ค€ํžˆ../C

[C : ls] C๋กœ ls ๊ตฌํ˜„ ์‹œ, -a ์˜ต์…˜ ์ฒ˜๋ฆฌ #getopt

by MIMI.L 2023. 12. 18.
๋ฐ˜์‘ํ˜•

์ด์ „ ํฌ์ŠคํŒ…์—์„œ getopt๋ฅผ ์•Œ์•„๋ดค๊ณ , ์ด๋ฒˆ์—” ls ๊ตฌํ˜„ ์‹œ -a ์˜ต์…˜์— ๋Œ€ํ•œ ์ธ์ž์ฒ˜๋ฆฌ๋ฅผ ํ•ด๋ณด๋ ค๊ณ  ํ•จ

๋‹ค๋ฅธ ์˜ต์…˜๋“ค๋„ ๋‚˜์ค‘์—.. ์–ธ์  ๊ฐ„.. ํ•ด๋ด์•ผ์ง€...

 

argc๊ฐ€ 1๊ฐœ์ธ์ง€ (ls ๋งŒ ์ž…๋ ฅ๋œ ๊ฒฝ์šฐ)

argc๊ฐ€ 1๊ฐœ๊ฐ€ ์•„๋‹Œ์ง€ (ls์™€ ์˜ต์…˜์ด ํ•จ๊ป˜ ์ž…๋ ฅ ๋œ ๊ฒฝ์šฐ)

๋ฅผ ๋‚˜๋ˆ ์„œ ์ž‘์„ฑ

 

argc๊ฐ€ 1๊ฐœ์ธ๊ฒฝ์šฐ .์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ˆจ๊น€ํŒŒ์ผ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ํŒŒ์ผ๋“ค์„ ์ถœ๋ ฅํ•˜๊ณ 

1๊ฐœ๊ฐ€ ์•„๋‹Œ๊ฒฝ์šฐ์—๋Š” getopt()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์˜ต์…˜์— ๋งž๊ฒŒ ์ถœ๋ ฅํ•˜๋„๋ก ๊ตฌํ˜„

 

ํ˜„์žฌ ์˜ต์…˜์€ a๋งŒ ์‚ฌ์šฉ !

 

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

int main(int argc, char* argv[]) {
    
    struct dirent *dir;
    int c;

    DIR *dp = opendir(".");
    if (dp == NULL) {
        return -1;
    }

    if (argc == 1) {
        while (dir = readdir(dp)) {
            if (dir->d_name[0] == '.')
                continue;
            else
                printf("%s  ", dir->d_name);
        }
        closedir(dp);
    }
    else {
        while( (c = getopt(argc, argv, "a")) != -1) {
            switch(c) {
                case 'a':
                    while (dir = readdir(dp)) {
                        printf("%s  ", dir->d_name);
                    }
                    break;
                case '?':
                    printf("Does not support %c\n", optopt);
            }
            closedir(dp);
        }
    }

    printf("\n");

    return 0;
}

 

์ปดํŒŒ์ผ ํ›„ ์‹คํ–‰ํžˆ์‹œํ‚ค๋ฉด,

์•„๋ž˜์™€ ๊ฐ™์ด

ls๋Š” ์ผ๋ฐ˜ ํŒŒ์ผ๋งŒ,

-a์˜ต์…˜์„ ์ฃผ๋ฉด ์ˆจ๊น€ํŒŒ์ผ๊นŒ์ง€ ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Œ

 

mimi@mimi:~/Mimi/lang/c$ ./ls
ls.c  echo.c  clean  clean.c  TDL.c  getopt.c  ls  

mimi@mimi:~/Mimi/lang/c$ ./ls -a
.vscode  ls.c  ..  .  echo.c  clean  clean.c  TDL.c  getopt.c  ls
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€