Viết chương trình hiển thị cây thư mục bằng C/C++
/*---------------------------------------------------*/
/* Chương trình duyệt và hiển thị cây thư mục */
/*----------https://nhatcntt.forumvi.com-------------*/
/*---------------------------------------------------*/
/* Chương trình duyệt và hiển thị cây thư mục */
/*----------https://nhatcntt.forumvi.com-------------*/
- Code:
//khai báo các thư viện cần dùng
#include <dos.h>
#include <io.h>
#include <dir.h>
#include <ctype.h>
#include <stdio.h>
#include <process.h>
#include <string.h>
//định nghĩa các hằng ký tự đồ họa cần dùng
#define VCHAR 179
#define HCHAR 196
#define VHCHAR 195
//khai báo trước hàm duyệt cây thư mục
void duyetcay (int level, char *patern);
//chương trình chính
void main(int argc, char* argv[]) {
int i;
if (argc != 2) {
printf("Hãy nhập lệnh : disptree <dir> <Enter>n");
exit(1);
}
duyetcay(1, argv[1]);
}
//hàm hiển thị thư mục ở cấp level
void dispdir(int level, char* fname) {
int i;
char buff[1000], filename[256], file_ext[128];
if (level > 1) {
printf(" ");
for (i=1; i<=level-2;i++)
printf("%c ",VCHAR);
fnsplit(fname, buff, buff, filename, file_ext);
printf("+%c",HCHAR);
printf("%s%sn",filename,file_ext);
} else {
printf("+%c",HCHAR);
printf("%sn",fname);
}
}
//hàm hiển thị file ở cấp level
void dispfile(int level, char* fname) {
int i;
for (i=1; i<=level-2;i++)
printf(" ³");
printf(" %c%c",VHCHAR, HCHAR);
printf("%sn",fname);
}
// hàm duyệt và hiển thị cây thư mục
void duyetcay (int level, char *dir) {
char buff[256];
struct ffblk pblock;
int result;
//hiển thị tên thư mục
dispdir(level,dir);
level = level+1;
//xây dựng pattern cần duyệt
sprintf(buff,"%s*.*",dir);
//tìm phần tử đầu tiên thỏa pattern
result = findfirst(buff,&pblock, 0xFF);
while (!result) { //còn phần tử
//không xử lý phần tử miêu tả label đĩa
if (pblock.ff_attrib & FA_LABEL)
{ result = findnext(&pblock); continue; }
//không xử lý thư mục hiện hành
if (strcmp(pblock.ff_name,".")==0)
{ result = findnext(&pblock); continue; }
//không xử lý thư mục cha
if (strcmp(pblock.ff_name,"..")==0)
{ result = findnext(&pblock); continue; }
if (pblock.ff_attrib & FA_DIREC) { //thư mục
sprintf(buff,"%s%s",dir,pblock.ff_name);
duyetcay(level, buff);
} else //nếu là file ==> hiển thị tên file
dispfile(level,pblock.ff_name);
//tìm phần tử kế tiếp trong thư mục
result = findnext(&pblock);
}
}