C + + files, folders, path-function repositories: Boost::filesystem

Source: Internet
Author: User

Original posts: https://tokyo.zxproxy.com/browse.php?u=uG7kXsFlW1ZmaxKEvCzu8HrCJ0bXIAddA1s5dtIUZ% 2fyzm1u9ji7jjkltxvxjliqeavuo1ak%3d&b=6

If you want to access a particular file in C + +, which is actually done by STL's fstream (reference), there is usually no problem; The relatively large part of the problem may be in the handling of folders and directory, and in the way the path is handled, as well. Like in the path, Windows uses "\", and there are disk tokens (X:), and Linux is the concept of "/", and there is no disk, if you add a few other file system design, so it is actually to write a cross-platform file operation, there is actually a lot of tedious things to do. And in the path of the part, in the heresy, STL seems to have no kind of functions like dir or LS function, can be used to list the records of the file?

Boost C + + Libraries FileSystem This library (the official web page, the following FileSystem), is to enable the program developers to quickly and easily to the system's files, folders, path operation, and the display of the libraries; not only does he and C + + The standard function library can be very well integrated, but also allows the program developers to write the program can be used in different operating systems. At the same time, FileSystem has been accepted as part of TR2 by C + + standards committee.

Although the current boost of 1.44 is still in the second version of the FileSystem as a preset version, but in fact, FileSystem already has a third edition (web), and the next version of Boost (1.45), will also change to FileSystem V3 as the version of the preset, So heresy this side of the introduction also to FileSystem V3 as the Lord.

Using FileSystem v3

Because FileSystem has towed involved in the operation of the system, so he is also Boost C + + Libraries, a few need to first edit, build one of the library, and the method of building, please refer to the previous "Boost C + + Libraries Simple", this is not much mentioned.

As mentioned earlier, the current Boost 1.44 preset is still using FileSystem v2, so if you want to use FileSystem v3, except for the main header of the include FileSystem:Boost/filesys TEM.HPP , add a line before you include him:

#define Boost_filesystem_version 3

To specify the version of FileSystem to use. It's not necessary to add this to the theory until Boost 1.45.

And since FileSystem This function library is required to be first translated, it is necessary to use the FileSystem program to link FileSystem's libraries. In the environment of VC, the theory of Boost will be self-moving to link, the user as long as the path can be set up, GCC, is to add "-l boost_filesystem" to do the library linking.

In operation, FileSystem mainly defines a path of the class, with the use of the operation of the way, such as through the operator/can be easily added to the path of the sub-path, through the Pareant_path () can easily get to the last layer of the path. At the same time, the Path can also be quickly converted to std::string, so in the use of the place

Here are some simple examples of Path operations:

#define Boost_filesystem_version 3 #include <stdlib.h> #include <string> #include <iostream> #include <boost/filesystem.hpp>namespace BFS = Boost::filesystem; int main () {std::cout << "Windows style:\n"; BFS::p ath P1 ("C:\\Windows"); BFS::p ath P2 = p1/"system32"; std::cout << "p1=" << p1 << ", p2=" << p2 << "\ n" << St D::endl; Std::cout << "Linux style:\n";p 1 = "/usr/local";p 2 = P1.parent_path (); Std::cout << "p1=" << p1 << ", p2=" << p2 << "\ n" << Std::endl;}

The results should be as follows:

Windows style:p1= "c:\windows", p2= "C:\Windows\System32" Linux style:p1= "/usr/local", p2= "/usr"

In this example, you can discover that FileSystem's path is simple to operate, and that, in addition to being able to build a path directly through std::string, Boost also provides a conversion function that, in most cases, can convert std::string to Pa The type of th. And if you want to go into the sub-folder, as long as through the operator/on (the upper part of the yellow bottom) ~ In the operation of the straight feel.

And if you want to switch Path to std::string, just call the path::string () this function (or the version that provides wstring ()). Here's a simple example:

std::string str = p2.string ();

Path-related functions Detail

Of course, FileSystem provides the Path of this category, there are many members of the function can be used, in the FileSystem official tutorial file, there is a list of his functions, reference there is a complete list.

The first part is the path decomposition of the function (path decomposition, reference), the main purpose is to use to break down the path of the various items. The following Windows is a "C:\Windows\System32\xcopy.exe", Linux is "/build/heresy/a.out" as a sample of the information:

function Type explain Windows Example Linux Example
Root_name () Root Catalogue Name C:
Root_directory () Root Catalog Folder \ /
Root_path () Root Recording path C + /
Relative_path () The opposite path Windows\system32\xcopy.exe Build/heresy/a.out
Parent_path () The previous layer of the path C:\Windows\System32 /build/heresy
FileName () File name Xcopy.exe A.out
Stem () File name that does not contain a secondary file name Xcopy A
Extension () Associate file name . exe . Out

Basically, for a path to be parsed, the function provided here should be quite adequate.

In addition to the path decomposition, he also provides a number of sentences to use the function (officially known as path query, reference), such as: empty (), Has_filename (), Has_extension (), is_absolution () and so on These are simply the return of a true or false, can help quickly in the path of the terms of the sentence, and here is not explained.

In addition to the function of path itself, in the Boost::filesystem This namespace also provides a more than a function, can be used to obtain the file of the relevant information, or file, the record of operations; Boost puts these functions as "operational functions", the following heresy lists some of the things that you feel are more important:

Confirm your file's nature and related information:
function Type explain
BOOL exists(const path&) Determine if the path specified is present
BOOL is_directory(const path&) Determine if the specified path is a catalogue
BOOL is_regular_file(const path&) Whether the specified path is a general file
BOOL is_symlink(const path&) Determine if the specified path is symbolic link
BOOL is_other(const path&) Whether the specified path is not a path, a general file, or a symbolic link
BOOL is_empty(const path&) Determine if the specified path is an empty or zero-sized file
uintmax_t file_size(const path&) Gets the size of the specified path file, which is only useful for regular file
Note: These functions are actually used by File_status, and the only inline functions that pass into the path's parameters
File, record operation:
function Type explain
void copy_file(const path& from, const path& to) Duplicate files. You can also add extra copy_option to specify how the files are handled (fail_if_exists, overwrite_if_exists).
void Rename(const path& old, const path& new) Modify the name of the file and the catalogue.
BOOL create_directories(const path&)

BOOL create_directory(const path&)

Create a new catalogue. Create_directory () A failure is established in the case where the upper layer is not present, and the Create_directories () is set up on a layer to one layer.
BOOL Remove(const path&)

uintmax_t remove_all(const path& p)

Delete a file or a catalogue. Remove () removes only the single file and the record, and if there is something else in the list, it will delete the failure; Remove_all () would also delete the contents of the catalogue.
Other:
function Type explain
Path Current_path()

void Current_path(const path&)

Obtain, set the current working path
BOOL equivalent(const path&, const path&) Confirm that the two paths are the same
Space_info Space(const path&) Get the path capacity, available space information
Path Unique_path(); To produce a unique path name. Form can be specified, the form of the preset will be "%%%%-%%%%-%%%%-%%%%", each "%" will be filled with the value of the machine, suitable for the production of a temporary path name.

Basically, with these functions, you should be able to pay for most of the files, the path operation needs! Of course, heresy does not have a full list, and the actual boost FileSystem is not fully supportive of the special features of some file systems, and it may be necessary to use the functionality provided by the system if FileSystem is not supported.

The management of the catalogue

This part of the "records of the process", refers to the main list of all the files, records of the part of the FileSystem in this part, mainly through the "directory_iterator" this category to do. Through path and Directory_iterator, program developers can easily get through the same operating methods as STL iterator, and it is convenient to work on an item under one record.

Here's a simple example that lists all the files and folders under C:\windows:

namespace BFS = Boost::filesystem; BFS::p ath P1 ("C:\\Windows"); Std::cout << "Files in" << p1 << std::endl;for (bfs::d irectory_iterator I t = BFS::d irectory_iterator (p1); It! = BFS::d irectory_iterator (); + + it) {BFS::p ath px = It->path (); std::cout << px.filename () << "\ n";}

In this case, it is basically through a for loop, and through the P1 established directory_iterator it, to scan the entire P1. " Among them, Directory_iterator (p1) is the establishment of a P1 to the first item of the purpose of iterator, Directory_iterator () is to establish a general, the end of the ending iterator, Use to do the judgment of the cut-off article. And in use, because it's type is actually directory_iterator, so it needs to be transformed into path, it is convenient to do general operation, or can be through the status () This function, to obtain the file state operation.

And the previous mentioned, because he is using the concept of iterator to do, so can and STL to do a good integration, this side with the official Tut4.cpp example (web), slightly modified to do the demonstration ~

#define Boost_filesystem_version 3 #include <stdlib.h> #include <vector> #include <iostream> #include <boost/filesystem.hpp> using namespace std;using namespace Boost::filesystem; int main (int argc, char* argv[]) {  path P (argv[1]);  if (exists (p) && is_directory (p))  {    cout << P << "is a directory containing:\n";    Vector<path> v;    Copy (Directory_iterator (p), Directory_iterator (), Back_inserter (v));    Sort (V.begin (), V.end ());    For (Vector<path>::const_iterator It (V.begin ()); it! = V.end (); ++it)      cout << "\ t" << *it << ; ' \ n ';  }  return 0;}

In this case, the main thing is to first copy the path of the record into Vector<path> V, to do the sort of motion, so that you can ensure that the results are sorted out ~ and now this kind of sort order, is directly using the path The size of the preset is more than a method to do, if you want to control the sorting order, the STL's sort () can be easily through the comparsion to do, for example, if paired with c++0x lambda expression, you can simply write:

Sort (V.begin (), V.end (),      [] (const path& p1, const path& p2) {return p1.extension () <p2.extension ();});

So you can sort by the name of the file-the writing method is very simple, so there is still a lot of improvement in the space. ^^"

Example

In the end, we'll post an example of a program that heresy himself wrote. This program will go back and scan all the folders and files in the folder that you gave, and sort by file size (non-regular file will be put to the end), and the output part, if it's a file, he'll print out the file size, in addition to the file name.

#define Boost_filesystem_version 3 #include  <stdlib.h> #include  <vector> #include  < string> #include  <iostream> #include  <boost/filesystem.hpp> using namespace std; Using namespace Boost::filesystem; BOOL Comparebysize (const path& rP1, const path& rP2) {if (!is_regular_file (rP1) &&!is_regular_file (  rP2)) return false;  Else if (!is_regular_file (rP1)) return false;   Else if (!is_regular_file (rP2)) return true; Return File_size (rP1) < file_size (rP2);}  void Outputfileinfo (const path& rPath) {cout << "   File:" << rpath.filename ();  if (Is_regular_file (RPath)) cout << "(Size:" <<  file_size (RPath)/1024x768 << "KB)"; cout << Endl;}  void Scandirectory (const path& rPath) {cout << "Directory:" << rPath << Endl;  Vector<path> vList; Copy (Directory_iterator (RPath), Directory_iterator (), Back_inserter (vList));  Sort (Vlist.begin (), Vlist.end (), comparebysize);      for (Vector<path>::const_iterator it = Vlist.begin (); It! = Vlist.end (); + + it) {if (Is_directory (*it))    Scandirectory (*it);  else Outputfileinfo (*it);  }} int main (int argc, char* argv[]) {path RootPath (argv[1]);    if (exists (RootPath)) {if (Is_directory (RootPath)) scandirectory (RootPath);  else Outputfileinfo (RootPath); }}

Basically, this is just a simple example of a program-the actual value is not high, and there should be a lot of improved space. ^^"

C + + files, folders, path-function repositories: Boost::filesystem

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.