나는 경로 이름을 사용하고 그 경로를 가로 지르는 프로그램을 작성하고 그것이 나오는 모든 파일 경로와 블록의 파일 크기를 인쇄 한 다음 디렉토리라면 dir 경로 이름과 크기를 블록 단위로 인쇄합니다.C에서 경로 통과
코드가 무한 루프로 끝나며 "상태를 가져 오지 못했습니다. 파일이 너무 많이 열립니다."라는 메시지가 계속 표시됩니다.
#include <dirent.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
struct stat statbuf;
struct dirent *direntp;
DIR *dirp;
if(stat(argv[1], &statbuf) == -1){
perror("Failed to get file status");
return 1;
}
else if(argc != 2){
perror("Invalid amount of arguments, showtreesize requires 1 pathname");
return 1;
}
else{
if(S_ISDIR(statbuf.st_mode) || S_ISREG(statbuf.st_mode)){
printf("%s %d", argv[1], depthfirstapply(argv[1], sizepathfun(argv[1])));
}
else{
if(S_ISCHR(statbuf.st_mode)){
printf("%s is a character special file.", argv[1]);
}
if(S_ISBLK(statbuf.st_mode)){
printf("%s is a block special file", argv[1]);
}
if(S_ISFIFO(statbuf.st_mode)){
printf("%s is a FIFO special file", argv[1]);
}
else{
printf("%s is not a valid filetype", argv[1]);
}
}
return 0;
}
}
int sum = 0;
int levelcount = 0;
int isDirectory(char *path){
struct stat statbuf;
if(stat(path, &statbuf) == -1)
return 0;
else
return S_ISDIR(statbuf.st_mode);
}
int depthfirstapply(char *path, int pathfun(char *path1)){
struct dirent *direntp;
DIR *dirp;
if(isDirectory(path)){
printf("%s\n", path);
if((dirp = opendir(path)) == NULL){
perror ("Failed to open directory");
return -1;
}
else{
while((direntp = readdir(dirp)) != NULL) {
if(isDirectory(direntp->d_name)){
int result = depthfirstapply(direntp->d_name, pathfun);
if (result > 0){
sum += result;
}
}
else{
if(pathfun(direntp->d_name) >= 0){
sum += pathfun(direntp->d_name);
}
}
}
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
}
}
else{
sum += pathfun(path);
}
return sum;
}
int sizepathfun(char *path){
struct stat statbuf;
if(stat(path, &statbuf) == -1){
perror("Failed to get file status");
return -1;
}
if(S_ISREG(statbuf.st_mode) == 0){
return -1;
}
else{
printf("%s %d", path, statbuf.st_blocks);
return statbuf.st_blocks;
}
}
왜'ftw()'를 쓰지 않으시겠습니까? – Barmar