C言語:カレントディレクトリ内にあるCファイルの行数を数えて表示

dirent構造体を使って、カレントディレクトリ内にあるCファイルの行数を数えて表示するプログラムを作った。
今まで自分が作ったC言語のプログラム(拡張子がcのファイル)の行数はどれくらいなのかな、と思って作成しただけなので誰の役にも立たないプログラムとなった。

実行例
()内の数値はそのファイルの行数

xTriplePrintf.c(21)
XtwoDimArray.c(23)
xTypedef.c(22)
xUnion.c(12)
xUruu.c(17)
xUsoTenki.c(28)
Xvoid.c(16)
Xwareki.c(14)
xWchar.c(26)
xWeight.c(20)
xWhile.c(22)
xWordQuestion.c(167)
XXX.c(15)
zei.c(15)

290ファイルありました
トータル行 = 11672

プログラム

1/*
2    countLine.c カレントディレクトリ内にあるCプログラムファイルごとに
3                行数を数えて表示
4     
5    Created by MRGARITA.NET on 2014/01/06.
6    Copyright 2014 Shuichi Takeda, All rights reserved.
7*/
8#include <stdio.h>
9#include <string.h>
10#include <dirent.h>
11 
12/*
13 * countRows ファイルを開いて行数をカウントする関数
14 */
15int countRows(char *fileName){
16    FILE *fp;
17    int count = 0;
18    int c;
19     
20    fp = fopen(fileName, "r");
21    if(fp == NULL){
22        printf("%s ", fileName);
23        perror("Error");
24        return count;
25    }
26    while((c = fgetc(fp)) != EOF){
27        if(c == '\n') count++;
28    }
29     
30    fclose(fp);
31    return count;
32}
33 
34/*
35 * メイン処理
36 */
37int main(void)
38{
39    DIR *dir;
40    struct dirent *ds;          /* ディレクトリストリーム構造体 */
41    char path[64] = ".\\"/* カレントディレクトリ */
42    char key[] = ".c";          /* Cプログラムの拡張子文字 */
43    int fileCount = 0;          /* Cプログラムのファイル数 */
44    int rows;                   /* ファイルごとの行数 */
45    int rowCount = 0;           /* トータルの行数 */
46     
47    dir=opendir(path);
48 
49    for(ds = readdir(dir); ds != NULL; ds = readdir(dir) ){
50        if(strstr(ds->d_name, key) != NULL){ // 拡張子「.c」ファイルのみ調べる
51            fileCount++;
52            // ファイルの行数をカウント
53            rows = countRows(ds->d_name);
54            rowCount += rows;
55            // ファイル名と行数を表示
56            printf("%s(%d)\n", ds->d_name, rows);
57        }
58    }
59    closedir(dir);
60     
61    printf("\n%dファイルありました\n", fileCount);
62    printf("トータル行 = %d\n", rowCount);
63    getchar();
64 
65    return 0;
66}

C言語ファイルのみ処理するためにreaddir関数とdirent構造体のd_nameで取得したファイル名と拡張子「.c」の文字列をstrstr関数の引数にしてチェックしている。

42char key[] = ".c";          /* Cプログラムの拡張子文字 */
43int fileCount = 0;          /* Cプログラムのファイル数 */
44int rows;                   /* ファイルごとの行数 */
45int rowCount = 0;           /* トータルの行数 */
46 
47dir=opendir(path);
48 
49for(ds = readdir(dir); ds != NULL; ds = readdir(dir) ){
50    if(strstr(ds->d_name, key) != NULL){ // 拡張子「.c」ファイルのみ調べる

コメント

タイトルとURLをコピーしました