判断dat文件是否存在,读文件大小,并将内容读取出来
#include <iostream>
#include <io.h> //_access
#include <string>
using namespace std;
#ifdef _MSC_VER
#define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#else
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#endif
#define INFO "info"
#define WARNING "warning"
#define ERROR "error"
#define LOG(n) std::cout << n << "|" << __FILENAME__ << ":" << __LINE__ << "->|"
#define LOG_END << std::endl;
int LoadDat(const char *cali_file_path);
bool check_file_exist(const std::string &path);
size_t GetFileSize(const string &filepath);
int main()
{
string path = "F:/1.dat";
LoadDat(path.c_str());
return 0;
}
int LoadDat(const char *cali_file_path)
{
if (NULL == cali_file_path) {
LOG(ERROR) << "Bad cali_file_path " LOG_END;
return -1;
}
if (!check_file_exist(cali_file_path)) {
LOG(ERROR) << "Cali file " << cali_file_path << " not exist " LOG_END;
return -2;
}
auto file_size = GetFileSize(cali_file_path);
if (file_size < 1000) {
LOG(ERROR) << "Bad cali file size " << file_size LOG_END;
return -3;
}
FILE *file = fopen(cali_file_path, "rb");
unsigned char *encode_cali_data = (unsigned char *)malloc(file_size);
fseek(file, 0, SEEK_SET);
fread(encode_cali_data, file_size, 1, file);
}
bool check_file_exist(const std::string &path) {
#ifdef _MSC_VER //https://blog.csdn.net/cocoasprite/article/details/54944785
bool ret = 0 == _access(path.c_str(), 0);
#else
bool ret = 0 == access(path.c_str(), F_OK);
#endif
if (!ret) {
LOG(INFO) << path << " not exist";
}
return ret;
}
size_t GetFileSize(const string &filepath) {
FILE *fd = fopen(filepath.c_str(), "rb");
if (fd == NULL) {
LOG(ERROR) << "Failed to open file " << filepath;
return 0;
}
// Determine size of the file
fseek(fd, 0, SEEK_END);
size_t file_length = static_cast<size_t>(ftell(fd));
fseek(fd, 0, SEEK_SET);
fclose(fd);
return file_length;
}