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
プログラム
/*
countLine.c カレントディレクトリ内にあるCプログラムファイルごとに
行数を数えて表示
Created by MRGARITA.NET on 2014/01/06.
Copyright 2014 Shuichi Takeda, All rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <dirent.h>
/*
* countRows ファイルを開いて行数をカウントする関数
*/
int countRows(char *fileName){
FILE *fp;
int count = 0;
int c;
fp = fopen(fileName, "r");
if(fp == NULL){
printf("%s ", fileName);
perror("Error");
return count;
}
while((c = fgetc(fp)) != EOF){
if(c == '\n') count++;
}
fclose(fp);
return count;
}
/*
* メイン処理
*/
int main(void)
{
DIR *dir;
struct dirent *ds; /* ディレクトリストリーム構造体 */
char path[64] = ".\\"; /* カレントディレクトリ */
char key[] = ".c"; /* Cプログラムの拡張子文字 */
int fileCount = 0; /* Cプログラムのファイル数 */
int rows; /* ファイルごとの行数 */
int rowCount = 0; /* トータルの行数 */
dir=opendir(path);
for(ds = readdir(dir); ds != NULL; ds = readdir(dir) ){
if(strstr(ds->d_name, key) != NULL){ // 拡張子「.c」ファイルのみ調べる
fileCount++;
// ファイルの行数をカウント
rows = countRows(ds->d_name);
rowCount += rows;
// ファイル名と行数を表示
printf("%s(%d)\n", ds->d_name, rows);
}
}
closedir(dir);
printf("\n%dファイルありました\n", fileCount);
printf("トータル行 = %d\n", rowCount);
getchar();
return 0;
}
C言語ファイルのみ処理するためにreaddir関数とdirent構造体のd_nameで取得したファイル名と拡張子「.c」の文字列をstrstr関数の引数にしてチェックしている。
char key[] = ".c"; /* Cプログラムの拡張子文字 */
int fileCount = 0; /* Cプログラムのファイル数 */
int rows; /* ファイルごとの行数 */
int rowCount = 0; /* トータルの行数 */
dir=opendir(path);
for(ds = readdir(dir); ds != NULL; ds = readdir(dir) ){
if(strstr(ds->d_name, key) != NULL){ // 拡張子「.c」ファイルのみ調べる


コメント