文件操作主要是获取文件在文件系统中的属性信息以及可能的改变操作。
#include <io.h> #include <stdio.h> /* int access(const char *filename, int amode); amode参数为0时表示检查文件的存在性,如果文件存在,返回0,不存在,返回-1。 这个函数还可以检查其它文件属性: 06 检查读写权限 04 检查读权限 02 检查写权限 01 检查执行权限 00 检查文件的存在性 */ if(0 != access(filename,0)){ printf("文件不存在\n"); }
#include <string> class cppFileUtil { public: // 获取文件名字,可以选择不包含后缀 static std::string basename(const std::string &filepath, bool nosuffix=false) { std::string rv = filepath; int idx = filepath.find_last_of('/'); if(idx != std::string::npos){ rv = filepath.substr(idx+1); } if(nosuffix){ idx = filepath.find_last_of('.'); if(idx != std::string::npos){ rv = rv.substr(0, idx); } } return rv; } // 获取文件后缀 static std::string suffix(const std::string &filepath) { int idx = filepath.find_last_of('.'); if(idx != std::string::npos){ return filepath.substr(idx+1); }else{ return ""; } } // 获取文件大小 static long filesize(const std::string &filepath) { std::ifstream in(filepath); in.seekg(0, std::ios::end); //设置文件指针到文件流的尾部 long size = in.tellg(); //读取文件指针的位置 in.close(); //关闭文件流 return size; } };