說明:
列出資樂夾裡的資樂夾和檔案
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <math.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <dirent.h>
#include <string.h>
#include <linux/usbdevice_fs.h>
#define BOOL int
#define TRUE 0
#define FALSE -1
#define MAX_LONG_LENGTH 1024
#define MAX_SHORT_LENGTH 128
#define MAX_MIDDLE_LENGTH 256
typedef enum FILEFOLDER_TYPE
{
ATTRIBUTE_FILE,
ATTRIBUTE_FOLDER,
}FILEFOLDER_TYPE_ENUM;
typedef struct filefolderInfo
{
char pathname[MAX_MIDDLE_LENGTH];
char name[MAX_MIDDLE_LENGTH];
FILEFOLDER_TYPE_ENUM type;
struct filefolderInfo *next;
}filefolderInfoS;
BOOL get_file_folder_list_fun(char *path, filefolderInfoS **p_list)
{
DIR *dir;
struct dirent *p_ptr;
filefolderInfoS *p_first = NULL;
filefolderInfoS *p_current = NULL;
dir =opendir(path);
if (dir == NULL)
return TRUE;
while((p_ptr = readdir(dir))!=NULL)
{
if ( strcmp(p_ptr->d_name, ".") == 0
|| strcmp(p_ptr->d_name, "lost+found") == 0
|| strcmp(p_ptr->d_name, "..") == 0)
{
continue;
}
if (strlen(p_ptr->d_name) > 1 && p_ptr->d_name[0] == '.')
continue;
char pathname[MAX_MIDDLE_LENGTH];
memset(pathname, '\0', MAX_MIDDLE_LENGTH);
struct stat buf;
sprintf(pathname,"%s%s", path, p_ptr->d_name);
stat(pathname, &buf);
filefolderInfoS *p_tmp = malloc(sizeof(filefolderInfoS));
strcpy(p_tmp->pathname, pathname);
strcpy(p_tmp->name, p_ptr->d_name);
p_tmp->next = NULL;
if(S_ISREG(buf.st_mode))
p_tmp->type = ATTRIBUTE_FILE;
else
p_tmp->type = ATTRIBUTE_FOLDER;
//printf("%s, %s, %d\n", p_tmp->pathname, p_tmp->name, p_tmp->type);
if (p_current == NULL)
{
p_first = p_tmp;
p_current = p_tmp;
}
else
{
p_current->next = (filefolderInfoS*)p_tmp;
p_current = p_tmp;
}
}
closedir(dir);
*p_list = p_first;
return TRUE;
}
void free_file_folder_list(filefolderInfoS *p_list)
{
filefolderInfoS *p_current, *p_next;
p_current = p_list;
while(p_current)
{
p_next = (filefolderInfoS*)p_current->next;
free(p_current);
p_current = p_next;
}
}
int main(int argc, char *argv[])
{
filefolderInfoS *p_info = NULL;
filefolderInfoS *p_tmp = NULL;
get_file_folder_list_fun("/etc/", &p_info);
p_tmp = p_info;
if (p_tmp)
{
while(p_tmp)
{
printf("file : %s, %s, %d\n", p_tmp->pathname, p_tmp->name, p_tmp->type);
p_tmp = p_tmp->next;
}
free_file_folder_list(p_info);
}
return 0;
}
Result:
file : /etc/acpi, acpi, 1
file : /etc/profile, profile, 0
file : /etc/rc4.d, rc4.d, 1
file : /etc/openal, openal, 1
file : /etc/apparmor.d, apparmor.d, 1
.............
沒有留言:
張貼留言