如何检查 filesystem::path 是否是一个文件?
How to check if a filesystem::path is a file?
我有一个写入二进制数据的函数,路径由用户提供。
如何检查给定的文件路径是否为可写文件路径?
is_regular_file()
returns false 对于给定的文件路径:
D:/SomePath
应该是可写文件(注意最后缺少的 /
)
D:/SomePath/File.txt
也是可写文件
D:/SomePath/File
是可写文件
D:/SomePath/SomeSubDir/
是一个目录。
#include <iostream>
#include <filesystem>
#include <string>
int main() {
using namespace std;
string file = "D:/SomeFile.txt";
string file2 = "D:/SomeFile";
string directory = "D:/Files/";
filesystem::path p1 = file;
filesystem::path p2 = directory;
filesystem::path p3 = file2;
cout << "file is_regular_file() : " << (filesystem::is_regular_file(p1) ? "true" : "false") << endl; //should return true
cout << "directory is_regular_file() : " << (filesystem::is_regular_file(p2) ? "true" : "false") << endl; // should return false
cout << "file_no_extension is_regular_file() : " << (filesystem::is_regular_file(p3) ? "true" : "false") << endl; // should return true
}
对 is_regular_file()
return 的所有三个调用都是错误的,尽管我希望第一个也是最后一个是 true
...
我在 windows,但这应该不是问题?
D:/SomePath
should be a writable file (note the missing /
at the end)
D:/SomePath/File.txt
is also a writable file
D:/SomePath/File
is a writable file
D:/SomePath/SomeSubDir/
is a directory.
我认为术语“可写文件”不适用于其中一些。你要问的是路径是否有文件名,std::filesystem::path
可以用 has_filename
.
测试
当然,这只是字符串测试的问题。它无法知道这是否表示文件系统中的实际 thing。这需要检查 filesystem::exists
.
我有一个写入二进制数据的函数,路径由用户提供。
如何检查给定的文件路径是否为可写文件路径?
is_regular_file()
returns false 对于给定的文件路径:
D:/SomePath
应该是可写文件(注意最后缺少的/
)D:/SomePath/File.txt
也是可写文件D:/SomePath/File
是可写文件D:/SomePath/SomeSubDir/
是一个目录。
#include <iostream>
#include <filesystem>
#include <string>
int main() {
using namespace std;
string file = "D:/SomeFile.txt";
string file2 = "D:/SomeFile";
string directory = "D:/Files/";
filesystem::path p1 = file;
filesystem::path p2 = directory;
filesystem::path p3 = file2;
cout << "file is_regular_file() : " << (filesystem::is_regular_file(p1) ? "true" : "false") << endl; //should return true
cout << "directory is_regular_file() : " << (filesystem::is_regular_file(p2) ? "true" : "false") << endl; // should return false
cout << "file_no_extension is_regular_file() : " << (filesystem::is_regular_file(p3) ? "true" : "false") << endl; // should return true
}
对 is_regular_file()
return 的所有三个调用都是错误的,尽管我希望第一个也是最后一个是 true
...
我在 windows,但这应该不是问题?
D:/SomePath
should be a writable file (note the missing/
at the end)D:/SomePath/File.txt
is also a writable fileD:/SomePath/File
is a writable fileD:/SomePath/SomeSubDir/
is a directory.
我认为术语“可写文件”不适用于其中一些。你要问的是路径是否有文件名,std::filesystem::path
可以用 has_filename
.
当然,这只是字符串测试的问题。它无法知道这是否表示文件系统中的实际 thing。这需要检查 filesystem::exists
.