Linux C + + variable the file name (including the filename of the subdirectory) in a directory

Source: Internet
Author: User
Tags strcmp

The recent write code has a need to traverse every file in the directory and get the absolute path to the file,

We know that there are system commands in Linux C + + so I made a log in the code, and then I read each line of the log file, and then I stored it.

1 voidGetFiles (vecotr<string>vecfilenames)2 {3 4     stringPath ="/home/yongchao/*.txt";5 6System"ls"+ Path +"> Temp.log"); 7 8Ifstream IFS ("/home/yongchao/temp.log")//variable log inside each file9      if(Ifs.fail ())Ten      { One            return; A       }   -        -      stringFileName; the        while(Getline (IFS, fileName)) -        { -Vecfilenames.push_back ("/home/yongchao/"+fileName); -         } +          - ifs.close (); + ifs.clear (); A        return; at}

As a result, it is conceivable that the project manager mercilessly criticized a meal, said I was too lazy, and then was laughed at colleagues are very ashamed .... First of all, this can not be recursive to save each subdirectory file, and then colleagues said that if you do temporary testing you can write these, but do projects can not do so ... A lesson from the bitter, obediently go online search for Linux C + + Traversal directory file name solution.

1#include <sys/types.h>2#include <sys/stat.h>3#include <dirent.h>///usr/include/dirent.h4#include <string>5#include <iostream>6 using namespacestd;7 8 intGetabsolutefiles (stringDirectory, vector<string>&filesabsolutepath)//parameter 1[in] Directory parameter to variable 2[out] Store file name9 {Tendir* dir =Opendir (Directory.c_str ());//Open Directory dir--> something like a directory handle One     if(dir = =NULL) A     { -cout<<directory<<"Is isn't a directory or not exist!"<<Endl; -         return-1; the     } -  -     structdirent* d_ent =NULL; Dirent--> stores various properties of the file -     Charfullpath[ -] = {0}; +     Chardot[3] =".";  Linux has one under each of them.  And.. To get rid of both of them. -     Chardotdot[6] =".."; +  A      while((d_ent = Readdir (dir))! =NULL)//A row of the contents of the Read directory, the property of this thing is placed in the dirent variable at     { -         if((strcmp (d_ent->d_name, dot)! =0) -&& (strcmp (d_ent->d_name, dotdot)! =0))//Ignore. and.. -         { -             if(D_ent->d_type = =Dt_dir)//d_type can see the current type of thing, Dt_dir represents the current directory, defined in Usr/include/dirent.h -             { in  -                 stringnewdirectory = Directory +string("/") +string(d_ent->d_name); The name of the subdirectory is stored in the D_name to                 if(Directory[directory.length ()-1] =='/') +                 { -newdirectory = Directory +string(d_ent->d_name); the                 } *  $                 if( -1==getabsolutfiles (NewDirectory, Filesabsolutepath))//recursive subdirectoryPanax Notoginseng                 { -                     return-1; the                 } +             } A             else//If it is not a directory the             { +                 stringAbsolutepath = Directory +string("/") +string(d_ent->d_name); Building an absolute path -                 if(Directory[directory.length ()-1] =='/')//If the incoming directory is finally/--> such as a/b/then the direct link file name $                 { $Absolutepath = Directory +string(d_ent->d_name); /a/b/1.txt -                 } - Filesabsolutepath.push_back (absolutepath); the             } -         }Wuyi     } the  - Closedir (dir); Wu     return 0; -}

Advanced Programming >> <<unix Environment

http://blog.csdn.net/zhuyi2654715/article/details/7605051

1 struct__dirstream2 3 {4 5 void*__fd;6 7 Char*__data;8 9 int__entry_data;Ten  One Char*__ptr; A  - int__entry_ptr; -  the size_t __allocation; -  - size_t __size; -  + __libc_lock_define (, __lock) -  + }; A  attypedefstruct__dirstream DIR;

The dir struct is similar to file and is an internal structure with several common functions
dir* opendir (const char* pathname); //
struct dirent* readdir (dir* dp); Iterate through the information in the directory
void Rewinddir (dir* dp); Re-reading directory information
int Closedir (dir* dp);
Long Telldir (dir* DP);
void Seekdir (dir* dp, long Loc);

Directory file: This file contains the names of other files and pointers to information about those files.
Dirent not only to the directory, but also to the specific files in the directory

structdirent{LongD_info;//inode Number Index nodeoff_t D_off;//offset to this dirent in the directory fileUnsigned ShortD_reclen;//Length of This d_name file lengths, note that the length here is not file size, size and length are two different things, you can use Lseek to move the file length is very long, but the size is actually so bigUnsignedCharD_type;//The type of d_name file type Chard_name[name_max+1];//File name (null-terminated) filename, initially 255}

From the above definition, dirent structure stored in the information about the file is very small, so dirent also plays an index role, if you want to get similar to the ls-l effect of the file information, you must have the following stat function
int stat (const char* file_name, struct stat* buf);

The Readdir function stores the read file name in the D_name member of the struct dirent
The function of the stat function is to get the details of the D_name file and store the details in the following stat structure

structstat{mode_t St_mode; //File access Permissionsino_t St_ino;//Index Node Numberdev_t St_dev;//the device number used by the filedev_t St_rdev;//Device number of the device filenlink_t St_nlink;//number of hard connections for the deviceuid_t St_uid;//owner user identification numbergid_t St_gid;//Group Identification Numberoff_t st_size;//file capacity in bytestime_t St_atime;//the last time the file was accessedtime_t St_mtime;//the last time the file was modifiedtime_t St_ctime;//The last time the file state was changedblksize_t st_blksize;//The size of the disk block that contains the fileblkcnt_t st_blocks;//the disk block that the file occupies};

If we want to get the detailed information about the B file under the A directory process:
The Opendir function opens directory A and returns the Dir struct C that points to directory a
Call the Readdir (c) function to read all the files (including subdirectories) in the directory, and return to the dirent structure D of all the files under directory a
Traverse D, call stat (d->name, stat* e) to get the details of each file stored in the stat struct E

Below is a program that prints all the files and directories in the directory

To introduce some other functions related to directory operations

#include <unitstd.h>

Get the current directory name

char* getcwd (char* buf, size_t size); -->buf will return the current directory name. Any errors that occur will return null. If the path length exceeds size, the value returned by errno to ERANGE.GETCWD will never have the symbol link's

char* getcwd (char* buf); --->getcwd is a dangerous function, it is generally strongly advised not to use it because you cannot determine how long the maximum directory length is.

Get the maximum system directory length

Long pathconf (char* path, int flag);

Change your current directory

Chdir/fchdir/chroot

int chdir (const char* pathname);---> Change the current directory according to the pathname, it only changes the directory where the program is located

int Fchidr (int fd);---> Change according to the Open FD (file descriptor) directory

int chroot (const char* path),---> Change the root directory of the program.

// change the current directory to the top level directory if (ChDir (".. ") = =-1) {     perror ("could not change currentworking directory\n" );      return ;}

#include <sys/stat.h>

#include <sys/types.h>

int mkdir (const char* dirname, mode_t mode); ---> Create a new directory, if this directory or file already exists, then the operation fails such as mkdir ("/home/yongchao", 0755); 0755 of 0 means octal

#incude <unistd.h>

int rmdir (char* pathname); ---> Delete pathname directory

Linux C + + variable the file name (including the filename of the subdirectory) in a directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.