Boost::filesystem's use of notes

Source: Internet
Author: User
Tags error code error handling function prototype tmp folder disk usage
Boost::filesystem Use small notes

http://blog.csdn.net/dourgulf/article/details/8589207

Boost Official document: http://en.highscore.de/cpp/boost/filesystem.html

1. The path object is a Cross-platform routing object. There are many ways to access various parts of a path, and also use its iterator to iterate through the various parts of the path;
Path constructs the directory structure using the "/" operator, very intuitive.
such as Path P1;
Path P2 = p1/"Something"; P1/= "Xxx.xxx";

2. FileSystem name Space There are some global functions, such as exists can determine whether the path exists, Is_directory function to determine whether the directory, file_size get the size-the size is a platform type, can represent 32 bits or 64 of the size;
Other is methods also include:

     Is_empty
     is_other
     is_regular_file
     is_symlink

3. One of the most convenient functions is to traverse all the content in the path.      Directory_iterator. Path P;
Directory_iterator (P) is the starting point of the iterator, and Directory_iterator () without parameters is the end point of the iterator.

You can also iterate recursively, and replace the above directory_iterator with Recursive_directory_iterator.

4. Create a table of contents.  In particular, it is mentioned that one method is bool Create_directories (const path& p); If P is a directory (that is, Is_diretory returns True). It recursively creates the entire directory structure, eliminating the hassle of creating one for yourself.

Other ways to create it are:

Create_directories
create_directory
create_hard_link
create_symlink

5. You can also copy catalogs
Copy_directory
copy_file
copy_symlink

6. Delete Remove recursive delete Remove_all


7. Change name Rename


8. If you include <boost/filesystem/fstream.hpp>, you can also let fstream accept path as a parameter.
BTW, the use of filesystem need to compile boost, now the version as long as the execution of a script can be compiled to complete, more convenient than before.
However, to mention the use of Xcode environment, to choose the GCC C + + standard library.


GCC cry Although there is no LLVM of the library advanced (I mean support c++11 aspect), however, most of the C++11 standards are supported.

Currently found to be GCC's library is not std::regex. But, with boost, it's better to use Boost's regex. Anyway, the STD is coming from boost.


forgotten the corner of the log more detailed

http://hi.baidu.com/lingyu125/item/7bb0a8cf73a8fe11b77a2460


Boost::filesystem

zz:http://www.ibm.com/developerworks/cn/aix/library/au-boostfs/#resources

For programs with more I/O operations, this inconsistency means that a lot of engineering work is required to migrate code between platforms. It is for this reason that we introduced the Boost filesystem Library. This widely used library provides a secure, portable, and Easy-to-use C + + interface for performing file system operations. This library can be downloaded free of charge from the boost site.

The first program that uses Boost::filesystem

Before delving into the more details of the Boost filesystem Library, take a look at the code shown in Listing 1, which uses the Boost API to determine whether a file type is Directory.

#include <stdio.h>
#include "boost/filesystem.hpp"
int main ()
{
boost::filesystem::p Ath Path ("/usr/local/include"); Random pathname
bool result = boost::filesystem::is_directory (path);
printf ("Path is a directory:%d" n ", result);
return 0;
}

This code is straightforward, and you don't need to know any system-specific routines. This code is validated to compile successfully on gcc-3.4.4 and cl-13.10.3077 without modification. Understanding the Boost Path Object

The key to understanding the Boost filesystem Library is the path object, because multiple routines defined in the FileSystem library operate on the corresponding Path object. File system paths usually depend on the operating system. For example, it is well known that UNIX and Linux systems use the forward slash (/) character as the directory separator, while Windows uses the backslash (") character for a similar purpose. Boost::filesystem::p Ath is designed to accurately abstract this attribute. The path object can be initialized in a variety of ways, most commonly by using char* or std::string, as shown in Listing 2.
Listing 2. How to create the Boost path object

Path (); Empty path
path (const char* pathname);
Path (const std::string& pathname);
Path (const char* pathname, Boost::filesystem::p ath::name_check checker);
Path (const char* pathname, Boost::filesystem::p ath::name_check checker);

When you initialize the path object, you can provide PATHNAME variables in a portable format defined by the native format or portable operating system interface (Portable operating system interface,posix) committee. Both of these methods have advantages and disadvantages in practice. Consider the following: you want to manipulate the directory created by the software, which is located on UNIX and Linux systems on/tmp/mywork, and on Windows in C: "tmp" mywork. There are several ways to handle problems. Listing 3 shows a method that is oriented to the native format.
Listing 3. Initializing path with native format

#ifdef UNIX
boost::filesystem::p Ath Path ("/tmp/mywork");
#else
boost::filesystem::p Ath Path ("C:" "tmp" "mywork");
#endif

A single #ifdef is required to initialize the path object by operating system. However, if you prefer to use the portable format, see Listing 4. Listing 4. Initializing path with portable format
Boost::filesystem::p Ath Path ("/tmp/mywork");

Note that Path::name_check refers to a name check function prototype. The name check function returns "True" if its parameter input PATHNAME is valid for a particular operating system or file system. The Boost filesystem Library provides multiple name checking functions, and you are also welcome to provide your own variants. The commonly used name checking function is the portable_posix_name and windows_name provided by Boost.

Path member function overview

The

Path object provides multiple member methods. These member routines do not modify the file system, but provide useful information based on the path name. This section provides an overview of several routines: const std::string& string (): This routine returns a copy of the string used to initialize path, in a format that conforms to the path syntax rule. std::string root_directory (): When a path is provided, the API returns the root directory, otherwise an empty string is returned. For example, if the path contains/tmp/var1, this routine will return/, that is, the root of the UNIX file system. However, if the path is a relative path, such as ... /mywork/bin, this routine returns an empty string. std::string root_name (): This routine returns a string containing the first character of PATHNAME, given the path starting at the root of the file system. std::string Leaf (): in the case of a given absolute path name (for example,/home/user1/file2), this routine provides a string (that is, file2) corresponding to the name of the file. std::string Branch_path (): This is a complementary routine with the leaf. In the case of a given path, all elements of its construction (except the last element) will be returned. For example, Path,path.branch_path () initialized with/A/B/C will return/a/b. For a path that contains a single element, such as C, this routine returns an empty string. bool Empty (): If the Path object contains an empty string (for example, Path path1 ("")), this routine returns TRUE. Boost::filesystem::p ath::iterator: This routine is used to traverse the various elements of the path. Take a look at the code shown in Listing 5.

Listing 5. Using Path::iterator (begin and end interfaces)

#include <iostream>
#include "boost/filesystem.hpp"
int main ()
{
Boost::filesystem::p Ath Path1 ("/usr/local/include"); Random pathname
boost::filesystem::p ath::iterator pathi = Path1.begin ();
while (Pathi!= path1.end ())
{
std::cout << *pathi << Std::endl;
++pathi;
}
return 0;
}
Result:1

The output of the program above is/, USR, local, include, which represents the hierarchical structure of the directory. path operator/(char* LHS, const path& RHS): This routine is a non-member function of path. It returns the concatenated value of the path formed using LHS and RHS. It will be automatically inserted/as the path separator, as shown in Listing 6.

Listing 6. Concatenation of Path strings

#include <iostream>
#include "boost/filesystem.hpp"
int main ()
{
Boost::filesystem:: Path path1 ("/usr/local/include"); Random pathname
boost::filesystem::p ath::iterator pathi = Path1.begin ();
while (Pathi!= path1.end ())
{
std::cout << *pathi << Std::endl;
++pathi;
}
return 0;
}
Result:1

Error Handling

File system operations often encounter unexpected problems, and the Boost filesystem Library will report run-time errors using C + + exceptions. The Boost::filesystem_error class derives from the Std::runtime_error class. The function in the library uses the Filesystem_error exception to report an operation error. Corresponding to the different possible error types, the Boost header file defines the appropriate error code. User code typically resides within a try...catch block and uses Filesystem_error exceptions to report related error messages. Listing 7 provides a small example of renaming a file that throws an exception when a file in the from path does not exist.
Listing 7. Error handling in Boost

#include <iostream>
#include "boost/filesystem.hpp"
int main ()
{
try {
Boost::filesystem ::p Ath Path ("C:" "src" "hdbase" "J1");
Boost::filesystem::p ath path2 ("C:" "src" "hdbase" "J2");
Boost::filesystem::rename (path, path2);
catch (Boost::filesystem::filesystem_error e) {
//do-needful
} return
0;

The function category Boost::filesystem in the Boost filesystem Library provides different categories of functions: Some functions (such as is_directory) are used to query the file system, while other functions such as Create_ directory), the file system is actively modified. Depending on their functionality, these functions can be roughly grouped into the following categories: Property Functions: provides miscellaneous information, such as file size, disk usage, and so on. file System action functions: for creating regular files, directories, and symbolic links, for copying and renaming files, and for deleting features. Utilities: test file extensions, and so on. Miscellaneous general functions: Programmatically changing the file name extension, and so on.

Property functions

The boost filesystem Library includes the following property functions: uintmax_t file_size (const path&): Returns the size (in bytes) of a regular file boost:: Filesystem::space_info Space (const path&): accepts the path as input and returns the SPACE_INFO structure defined below: struct Space_info {
uintmax_t capacity;
uintmax_t free;
uintmax_t available;
}; Depending on the disk partition to which the file system belongs, this process returns the same disk usage statistics (in bytes) for all directories of the partition. For example, for C: "SRC" Dir1 and C: "src" dir2, the same disk usage data will be returned. std::time_t last_write_time (const path&): Returns the last modification time of a file. void Last_write_time (const path&, std::time_t new_time): modifies the last modification time of a file. Const path& Current_path (): returns the full path of the program's current working directory (note that this path may be different from the path that originally ran the program, because the directory may be changed programmatically).

File System action Functions

This set of functions is responsible for new file and directory creation, file deletion, and other operations:bool Create_directory (const path&):This function creates a directory with the given path name. (Note that if the PATHNAME itself contains invalid characters, the results are often defined by the platform.) For example, in UNIX and Windows systems, the asterisk (*), question mark (?), and other such characters are considered invalid and cannot appear in the directory name. )bool Create_directories (const path&):As opposed to creating a single directory, you can use this API to create a directory tree. For example, in the case of a directory tree/a/b/c, you must create this tree in the/tmp folder. This API can be invoked to complete a task, but an exception is thrown when Create_directory is invoked with the same parameters.bool Create_hard_link (const path& frompath, const path& topath):This function creates a hard link between frompath and Topath.bool Create_symlink (const path& frompath, const path& topath):This function creates a symbolic (soft) link between frompath and Topath.void Copy_file (const path& frompath, const path& topath):Copy the contents and properties of the file referenced by Frompath to the file referenced by Topath. Routinesexpects a destination file to be absent; If there is a destination file, an exception is thrown. Therefore, this function is not equivalent to the CP command specified by the system in UNIX. In addition, this function expects the Frompath variable to refer to the correct regular file. Consider the following example: Frompath reference Symbolic Link/tmp/file1, which in turn refers to file/tmp/file2, while Topath can be/tmp/file3. In this case, Copy_file will fail. This is another difference between this API and the CP command.void Rename (const path& frompath, const path& topath):This function is the API for renaming files. You can rename and change the location of the file at the same time by specifying the full path name in the Topath parameter, as shown in Listing 8.

Listing 8. The rename feature in Boost

#include <stdio.h>
#include "boost/filesystem.hpp"
int main ()
{
boost::filesystem::p Ath Path ("/home/user1/abc");
Boost::filesystem::rename (Path, "/tmp/def");
return 0;
}
bool Remove (const path& p):This routine will attempt to delete the file or directory referenced by the path p. In the case of a directory, this routine throws an exception if the contents of the directory are not empty. Warning: This routine does not consider the deleted content, even if other programs are accessing the same file. unsigned long remove_all (const path& p):This API attempts to delete the file or directory referenced by the path p. Unlike remove, this function does not give special consideration to directories that are not empty. This function is the Boost equivalent of the UNIXRM–RF command.

Practical Tools

The

Boost filesystem Library contains the following utilities: BOOL exists (const path&): This function checks the file extension. Files can be of any type: regular files, directories, symbolic links, and so on. bool Is_directory (const path&): This function checks whether the path corresponds to the directory. bool Is_regular (const path&): This function checks the normal file (that is, this file is not a directory, symbolic link, socket, or device file). bool Is_other (const path&): Typically, this function checks device files (such as/dev/tty0) or socket files. bool Is_empty (const path&): If the path corresponds to a folder, this function checks to see if the folder is empty and returns "True" or "False" accordingly. If the path corresponds to a file, this function checks to see if the file size is equal to 0. For a hard link or symbolic link to a file, this API checks to see if the original file is empty. bool Equivalent (const path1& p1, const path2& p2): This API is very practical and can be used to compare relative paths and absolute path names. Take a look at Listing 9:

Listing 9. Testing two paths is equivalent

#include <stdio.h>
#include "boost/filesystem.hpp"
int main ()
{
Boost::filesystem::p Ath Path1 ("/usr/local/include"); Random pathname
boost::filesystem::p ath path2 ("/tmp/. /usr/local/include ");
BOOL result = Boost::filesystem::is_equivalent (path1, path2);
printf ("Paths are equivalent:%d" n ", result);
return 0;
}
path System_complete (const path&):This function is another API with a series of bool equivalent (const path1& p1, const path2& p2). This API returns the absolute path of the file, given the path to any file in the current working directory. For example, if the user is in the directory/home/user1 and queries the file ... /user2/file2, this function returns/HOME/USER2/FILE2, the full pathname of the file file2.

Miscellaneous functions

The Boost filesystem Library includes the following miscellaneous functions: std::string Extension (const path&): This function returns the extension of the given file name in the form of a period (.). For example, for a file with a file name of test.cpp, extension will return. cpp. This function returns an empty string for cases where the file does not have an extension. For hidden files (that is, file names in UNIX systems.) Starting file), this function evaluates the extension type appropriately or returns an empty string (therefore, for. Test.profile, this routine returns. Profile). std::string basename (const path&): This is a complementary routine with extension. It will return the file name. Before the string. Note that even if an absolute file name is provided, the API will only return a direct portion of the file name, as shown in Listing 10.

Listing 10. Using Boost::basename

#include <stdio.h>
#include <cstring>
#include "boost/filesystem.hpp" use
namespace std;
int main ()
{
boost::filesystem::p ath path1 ("/tmp/dir1/test1.c");
Boost::filesystem::p ath path2 ("/tmp/dir1/.test1.profile");
String result1 = Boost::filesystem::basename (path1);
String result2 = Boost::filesystem::basename (path2);
printf ("Basename 1:%s Basename2:%s" n ", Result1.c_str (), Result2.c_str ());
return 0;
}
std::string change_extension (const path& oldpath, const std::string new_extension):This API returns a new string that reflects the changed name. Please note that the file corresponding to the OldPath remains not change。 This is just a regular function. Also note that you must explicitly specify a point in the extension. For example, Change_extension ("test.c", "so") will get Testso, not test.so. From the boost.org
Only. The May is useful for dealing with legacy compilers or operating systems.

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.