Linux,  Programming

[Linux] wc 명령어 구현

#include <stdio.h>
#define RETURN_NUM 3

int get_width(int num) {
    int i;
    for(i=0; num!=0; i++) {
        num /= 10; 
    }   
    return i;
}

int main(int argc, char **argv) {
    FILE *fp;
    int ch, flag = 0;
    int count[RETURN_NUM] = {0,};
    int w, width = 0;
    fp = fopen(argv[1], "r");
    while((ch = fgetc(fp)) != EOF) {
        if(ch == '\n')
            count[0]++; // # of lines
        if(ch != '\n' && ch != ' ' && ch != '\t') {
            if(flag == 0) {
                count[1]++;
                flag = 1;
            }   
        } else {
            flag = 0;
        }   

        count[2]++;     // # of words
    }   

    for(int i=0; i<RETURN_NUM; i++) {
        w = get_width(count[i]);
        if(width < w)
            width = w;
    }   

    printf("%*d %*d %*d %s\n", width, count[0], width, count[1], width, count[2], argv[1]);
    fclose(fp);
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *