[C++] POCO learning summary (11): File system (path, file attributes, directory browsing, temporary files, etc.)

[C++] Guo Laoer’s blog post: C++ directory

1. Path

1.1 Path description

Window:
Path: C:\Windows\system32\cmd.exe
Style: Windows
Kind: absolute, to file
Node Name: –
Device Name: C
Directory List: Windows, system32
File Name: cmd.exe
File Version:

Linux:
Path: /usr/local/include/Poco/Foundation.h
Style: Unix
Kind: absolute, to file
Node Name: –
Device Name: –
Directory List: usr, local, include, Poco
File Name:Foundation.h
File Version:

1.2 Poco::Path represents the path

Header file: #include "Poco/Path.h"
Poco::Path does not care whether the path it contains actually exists in the file system

1.3 Examples of composing paths

#include "Poco/Path.h"
int main(int argc, char** argv)
{
    
    
	Poco::Path p(true); // path will be absolute
	p.setNode("VMS001");
	p.setDevice("DSK001");
	p.pushDirectory("POCO");
	p.pushDirectory("INCLUDE");
	p.pushDirectory("POCO");
	p.setFileName("POCO.H");
	std::string s(p.toString(Poco::Path::PATH_VMS));
	// "VMS001::DSK001:[POCO.INCLUDE.POCO]POCO.H"
	p.clear(); // start over with a clean state
	p.pushDirectory("projects");
	p.pushDirectory("poco");
	s = p.toString(Poco::Path::PATH_WINDOWS); // "projects\poco\"
	s = p.toString(Poco::Path::PATH_UNIX); // "projects/poco/"
	s = p.toString(); // depends on your platform
	return 0;
}

1.4 Example of parsing paths

#include "Poco/Path.h"
using Poco::Path;
int main(int argc, char** argv)
{
    
    
	Path p("c:\\projects\\poco\\build_vs80.cmd", Path::PATH_WINDOWS);
	std::string device(p.getDevice()); // "c"
	int n = p.depth(); // 2
	std::string dir1(p.directory(0)); // "projects"
	std::string dir2(p[1]); // "poco"
	std::string fileName(p[2]); // "build_vs80.cmd"
	fileName = p.getFileName();
	std::string baseName(p.getBaseName()); // "build_vs80"
	std::string extension(p.getExtension()); // "cmd"
	p.setBaseName("build_vs71");
	fileName = p.getFileName(); // "build_vs71.cmd"
	return 0;
}

1.5 Commonly used static functions

Poco::Path provides static methods to get the path of a system-specific special directory or file:

  • std::string current() returns the path of the current working directory
  • std::string home() returns the path to the user's home directory
  • std::string temp() returns the path of the temporary file to the system directory
  • std::string null() returns the path to a system empty file/device (for example, "/dev/null" or "NUL:")
  • bool find(const std::string& pathList, const std::string& name, path & path)
    Searches for a file with the given name at the location specified in pathList document.
    Paths in pathList must be separated by the platform's path separator (";" on Windows, ":" on Unix).
    If the file is found at one of the locations given in pathList, the absolute path to the file is stored in path and true is returned.
    Otherwise, return false and path remains unchanged.

2. Poco::File file

Header file: #include “Poco/File.h”

2.1 Query file attributes

  • bool exists() const: if fileexistReturns true, otherwise returns false
  • bool canRead() const: if the file isreadableReturns true (the user has sufficient permissions to read from the file), otherwise returns false
  • bool canWrite() const: if the file iswritable(the user has sufficient permissions to write to the file) returns true, otherwise returns false
  • bool canExecute() const: if the file isExecutableReturns true, otherwise returns false
  • bool isFile() const: if the file isOrdinary document(instead of a directory or symbolic link), false otherwise
  • bool isLink() const: if the file issymbolic linkReturns true, otherwise returns false
  • bool isDirectory() const: if the file isTable of contentsReturns true, otherwise returns false
  • bool isDevice() const: if the file isdevice fileReturns true, otherwise returns false
  • bool isHidden() const: If the file hasHidden properties(Windows), or whose name starts withpointBeginning (Unix), returns true
  • Poco::Timestamp created() const: return filecreatedate and time
  • Poco::Timestamp getLastModified() const: The returned file isaccessdate and time
  • File::FileSize getSize() const: Returns the size of the file in bytessize, File::FileSize is an unsigned 64-bit integer.

2.2 Modify file attributes

  • void setLastModified(Poco::Timestamp dateTime): Set the access timestamp of the file
  • void setSize(FileSize newSize): Set the size of the file in bytes, such as truncating the file
  • void setWritable(bool flag = true): Make the file writable (flag = true), or read-only (flag = false)
  • void setReadOnly(bool flag = true): Same as setWritable(!flag)

2.3 Rename, copy, delete, create

  • void copyTo(const std::string& path) const: Copy the file to the given path (can be a directory)
  • void moveTo(const std::string& path) const: Copy the file to the given path (can be a directory), and then delete the original file
  • void renameTo(const std::string& path): Rename the file
  • void remove(bool recursive = false): Delete the file. If the file is a directory and recursive=true, all files and subdirectories under the directory are deleted recursively.
  • bool createFile(): Creates a new empty file in an atomic operation. Returns true if the file has been created; false if the file already exists. If creation fails, Poco::FileException is thrown.
  • bool createDirectory(): Returns true if the creation is successful; returns false if the directory already exists. If creation fails (for example, if the parent directory does not exist), a Poco::FileException is thrown.
  • void createDirectories(): Create a directory and all required parent directories

2.4 Reading files in the directory

void list(std::vectorstd::string& files) const
void list(std::vector& files) const

3. Poco::DirectoryIterator directory iterator

Poco::DirectoryIterator provides an iterator-style interface for reading the contents of a directory.
Header file: #include "Poco/DirectoryIterator.h"
Poco::DirectoryIterator maintains a Poco::File and an absolute path Poco::Path.

#include "Poco/DirectoryIterator.h"
#include <iostream>
using Poco::DirectoryIterator;
using Poco::Path;
int main(int argc, char** argv)
{
    
    
	std::string cwd(Path::current());
	DirectoryIterator it(cwd);
	DirectoryIterator end;
	while (it != end)
	{
    
    
		std::cout << it.name();
		if (it->isFile())
			std::cout << it->getSize();
		std::cout << std::endl;
		Path p(it.path());
		++it;
	}
	return 0;
}

4. Pattern matching

Poco::Glob, in pattern:

  • '*' Matches any sequence of characters
  • '?'matches any single character
  • [SET] Matches any single character in the specified set
  • [!SET] matches any single character that does not belong to the specified character set
  • [123] Matches the number 1, 2 or 3
  • [a-zA-Z] matches any lowercase or uppercase letter
  • Special characters can be escaped with backslashes.

bool match(const std::string& subject): If the path in subject matches the pattern of Glob, return true, otherwise return false.

#include <iostream>
using Poco::Glob;
int main(int argc, char** argv)
{
    
    
	std::set<std::string> files;
	Glob::glob("%WINDIR%\\system32\\*.exe", files);
	// Glob::glob("/usr/include/*/*.h", files);
	std::set<std::string>::iterator it = files.begin();
	for (; it != files.end(); ++it)
	{
    
    
		std::cout << *it << std::endl;
	}
	return 0;
}

5. Poco::TemporaryFile temporary file

5.1 Description

Many programs require temporary files with the following characteristics:

  • Creates a temporary file in a special system-specific directory (for example, "/tmp/" on Unix systems).
  • Temporary files have automatically generated unique names
  • Temporary files must be deleted when they are no longer in use

Poco::TemporaryFile is derived from Poco::File. The constructor automatically creates a unique file name and places it in a system-specific temporary file directory. The file itself is not created. If the file has already been created, the destructor deletes the file. Alternatively, deletion can be deferred until program termination, or not deleted at all.

5.2 Use

  • void keep(): prohibit the destructor from automatically deleting files
  • void keepUntilExit(): Disables the destructor from automatically deleting the file and registers the file for deletion when the program terminates
  • static void registerForDeletion(const std::string& path): Register a file to be automatically deleted when the program terminates
  • static std::string tempName() creates a unique pathname for the temporary file

Guess you like

Origin blog.csdn.net/u010168781/article/details/134935891