1.判断一个文件是否存在,IsFileExists()
bool IsFileExists(const std::string &file_name) {std::ifstream fin(file_name);if (fin) {return true;} else {std::cout << file_name << " is not exist" << std::endl;return false;}return true;}
2.提取一个文件名称,并去掉扩展名,然后新建一个同名的不同扩展名文件:
这种做法一般用来根据某个文件来新建另一个与之相关联的文件,如,提取出/home/username/work/panda.txt
中的/home/username/work/panda
,并新建一个/home/username/work/panda.doc
文件。
std::string file_path="/home/username/work/panda.txt";//查找file_path是否有".txt"子串。返回找到的位置索引const size_t find = file_path.find(".txt"); if (find == std::string::npos) {// npos表示一个不存在的位置,就是没找到std::cout << "Cannot find file: " << file_path;return false;}// 将 file_path字符串从0~find位置组成的子串赋值给pathconst std::string path = file_path.substr(0, find);//std::string doc_path = path + ".doc";std::cout << "TRT model will saved to " << engine_path_ << std::endl;
std::string
中find()
函数返回值是字母或子串在母串中的位置(下标记录);
如果没有找到,那么会返回一个特别的标记npos
。std::string::npos
是一个常熟,它等于size_type
类型可以表示的最大值,用来表示一个不存在的位置。
更详细的解释请参考博客:C++ string中的find()相关函数使用说明 原文链接
返回子串出现在母串中的首次出现的位置,和最后一次出现的位置:
flag = "c";position = s.find_first_of(flag);printf("s.find_first_of(flag) is :%d\n",position);position = s.find_last_of(flag);printf("s.find_last_of(flag) is :%d\n",position);