Linux文件夹的操作

1、DIR,是directory的缩写,是思。DIR也是是DOS操作系统用来查看磁盘中文件的命令dir有很多的参数。

2、头文件:#include <dirent.h>

3、对应结构体如下:

struct dirent
{
  long d_ino; /* inode number 索引节点号 */
  off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
  unsigned short d_reclen; /* length of this d_name 文件名长 */
  unsigned char d_type; /* the type of d_name 文件类型 */
  char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}
struct__dirstream
{
void*__fd; /* `struct hurd_fd' pointer for descriptor.   */
char*__data; /* Directory block.   */
int__entry_data; /* Entry number `__data' corresponds to.   */
char*__ptr; /* Current pointer into the block.   */
int__entry_ptr; /* Entry number `__ptr' corresponds to.   */
size_t__allocation; /* Space allocated for the block.   */
size_t__size; /* Total valid data in the block.   */
__libc_lock_define(, __lock) /* Mutex lock for this structure.   */
};
typedefstruct __dirstream DIR;

4、struct dirent结构体相应的函数:

opendir(),readdir(),closedir()

opendir():
头文件:#include <sys/types.h>
#include <dirent.h>
函数原型
DIR* opendir(const char * path );

函数功能:打开一个目录,在失败的时候返回一个空的指针。

readdir():
语法: struct dirent*readdir(DIR* dir_handle);

返回值: dirent的结构类型

函数种类: 文件存取

内容说明 本函数用来读取目录。返回是dirent结构体指针

closedir():
closedir()关闭参数dir所指的目录流。关闭成功则返回0,失败返回-1,错误原因存于errno中。EBADF 参数dir为无效的目录流。

注意:目录文件作为一种文件,在打开必须关闭,否则会由于文件的进程打开文件过多而不能打开新的文件。因此opendir函数和closedir函数同样是配对出现的。

5、示例程序:

程序功能:从当前目录的文件夹test中读取所有文件,把所有文件的文件名存放在链表上,输出打印。对每一个对文件进行读操作,按照行进行操作,在屏幕上打印文件里的字符串。

源程序如下:

#include<stdio.h>
#include<dirent.h>
/*#include<alloc.h>*/
#include <string.h>
#include<stdlib.h>
#if 0
struct dirent
{
   long d_ino; /* inode number 索引节点号 */
   off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
   unsigned short d_reclen; /* length of thisd_name 文件名长 */
   unsigned char d_type; /* the type of d_name 文件类型 */
   char d_name [NAME_MAX+1]; /* file name(null-terminated) 文件名,最长255字符 */
}
struct __dirstream
{
    void *__fd; /* `struct hurd_fd' pointer fordescriptor.   */
    char *__data; /* Directory block.   */
    int __entry_data; /* Entry number `__data'corresponds to.   */
    char *__ptr; /* Current pointer into theblock.   */
    int __entry_ptr; /* Entry number `__ptr'corresponds to.   */
    size_t __allocation; /* Space allocated forthe block.   */
    size_t __size; /* Total valid data in theblock.   */
    __libc_lock_define (, __lock) /* Mutex lockfor this structure.   */
};
typedef struct__dirstream DIR;
#endif
 
int main(intargc,char *argv[])
{
    DIR *directory_pointer; //DIR是directory的缩写,是目录的意思
    struct dirent *entry;
    struct FileList
    {
            char filename[64];
            structFileList *next;
    }start,*node;
    FILE *fp = NULL;
    char buffer[20]="\0";
    if (argc!=2)
    {
            printf("Must specify adirectory\n");
            exit(1);
    }
    if((directory_pointer=opendir(argv[1]))==NULL)
            printf("Erroropening %s\n",argv[1]);
    else
    {
            start.next=NULL;
            node=&start;
            while((entry=readdir(directory_pointer))!=NULL)
            {
                   node->next=(structFileList *)malloc(sizeof(struct FileList));
                   node=node->next;
                   node->next= NULL;
                   strcpy(node->filename,entry->d_name);
                   if(strcmp(node->filename,".")==0||strcmp(node->filename,"..")==0)
                   {
                           //printf("node->filenameerror\n");
                           continue ;            
                   }
                   else
                   {
                           charpath[50]="./test/";
                           strcat(path,node->filename);
                           printf("filename=%s\n",node->filename);
                           printf("path=%s\n",path);
                           fp =fopen(path,"r");
                           if(fp== NULL)
                           {
                                  printf("%d\n",fp);
                           printf("cannotopen this file!\n");
                           continue;
                           }
                           while(!feof(fp))
                           {
                                  if(fgets(buffer,127,fp)== NULL)
                                  break;
                           buffer[strlen(buffer)-1]= '\0';     
                                  printf("%s\n",buffer);
                           }                     
                   }
                   node->next=NULL;
            }
            closedir(directory_pointer);
            node=start.next;
            while(node)
            {
                   printf("%s\n",node->filename);
                   node=node->next;
            }
    }
    system("pause");
    return0;
}

代码片段示例2:

struct FileList
{
	char file_path[64];
    struct FileList *next;
};

struct FileList *Folder(char *foldername);
int FileExtract(struct FileList *node);
struct FileList *Folder(char *foldername)
{
	DIR *directory_pointer;                         //define a folder directory pointer to folder
	struct dirent *entry; 
	struct FileList start,*node;

	if ((directory_pointer=opendir(foldername))==NULL)
	{
		printf("Error opening %s\n",foldername);
		return NULL;
	}
    	
    else
	{
		start.next=NULL;
		node=&start;
		while ((entry=readdir(directory_pointer))!=NULL)
    	{
    		if(strcmp(entry->d_name,".")!=0 && strcmp(entry->d_name,"..")!=0)
    		{
    			char path[50]="./";
				strcat(path,foldername);
				strcat(path,"/");            // relative paths,
				
      			node->next=(struct FileList *)malloc(sizeof(struct FileList));
      			node=node->next;
      			node->next = NULL;
      			strcpy(node->file_path,entry->d_name); //entry->d_name means file name
      			strcat(path,node->file_path);
      			strcpy(node->file_path,path);       //node->file_path means file the absolute path
    		}   		
    	}
		closedir(directory_pointer);
		/*

		*for test,output all file of file_path
		*/
		node=start.next;
		return node;
  	}
}

int FileExtract(struct FileList *node,map<string,int>mapword[])
{
	char buffer[MaxLine] = {'\0'};
	FILE *fp = NULL;
	int file_nodes = 0;
	while(node)
  	{
  		fp = fopen(node->file_path,"rb");
      	if(fp == NULL)
    	{
        	printf("cannot open this file!\n");
        	continue;
    	}
      	while(!feof(fp))
      	{
			if(fgets(buffer,MaxLine,fp) == NULL)
           		break;
        	buffer[strlen(buffer)-1] = '\0';	
			SegmentSentenceMM(buffer,mapword,file_nodes);//calling SegmentSentenceMM function Processes punctuation
		}	
		file_nodes++;
		node = node ->next;	
  	}
  	return file_nodes;
}

void DisFolderFilesName(struct FileList *node)
{
	while(node)
    	{
      		printf("%s\n",node->file_path);
      		node = node->next;
    	}
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值