在C ++中检查文件是否存在 [英] Checking for file existence in C++
问题描述
目前我使用类似:
#include <sys/stat.h>
#include "My_Class.h"
void My_Class::my_function(void)
{
std::ofstream my_file;
struct stat file_info;
if ( filename_str.compare("")!=0 &&
stat(filename_str.c_str(),&file_info) == 0 )
{
my_file.open(filename_str.data(),std::ios::trunc);
//do stuff
my_file.close();
}
else if ( filename_str.compare("")==0 )
{
std::cout << "ERROR! ... output filename not assigned!" << std::endl;
}
else
{
std::cout << "ERROR! File :" << std::endl
<< filename_str << std::endl
<< "does not exist!!" << std::endl;
}
}
...这是一个不错的方法,或有更好的替代品?似乎我可以运行权限的权限,如果我没有权限读取该文件。
...is this a decent way to go, or is there a better alternative? Seems like I could run amuck of permissions if I don't have permissions to read the file.
这不是一个家庭作业,问题,这是一个关于最佳实践的问题。
This is NOT a homework, question, it is a question about best practice.
推荐答案
通常我认为最好是尝试打开它并捕获错误。
Generally I think it is best to just try opening it and catch an error.
IMO,检查权限是不明智的,因为如果它是一个Linux框,并检查其属性,决定你不能写入,但文件系统支持ACL,他们做授予您权限? (作为系统管理员我不能立场当应用程序这样做我喜欢ACL的,如果你是一个应用程序,不要告诉我,你不能写一个文件,除非你尝试第一。)
IMO, checking permissions is unwise because what if it's a Linux box and you check its attributes, decide you can't write to it, but the filesystem supports ACL's and they do grant you permission? (As a sysadmin I can't stand when apps do this. I like ACL's and if you're an app, don't tell me you can't write to a file unless you've tried first.)
这篇关于在C ++中检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!