1.从txt文件中按指定格式 读出:
int read_raw_hex_data(const char* path,int data_length ,int* a) {
FILE* fpRead = NULL;
int ret = 0;
int i = 0;
fopen_s(&fpRead, path, "r");
if (fpRead == NULL)
{
printf("Fail to read raw data file!");
ret = -1;
return ret;
}
for (i = 0; i < data_length; i++)
{
fscanf_s(fpRead, "%x", &a[i]);
}
fclose(fpRead);
return ret;
}
2. 按指定格式保存到txt文件中:
int save_data(const char* path, int data_length, double* a) {
FILE* fpWrite = NULL;
int i = 0;
fopen_s(&fpWrite, path, "w");
if (fpWrite == NULL)
{
printf("Failed to save data!");
exit(1);
}
for (i = 0; i < data_length; i++)
fprintf(fpWrite, "%.8f\n", a[i]);
fclose(fpWrite);
return 0;
}
3. 获取txt文件行数
//summarize the data count of a file
int data_count_sum(const char* file_name) {
FILE* fp;
int num = 1;
char tmp;
fopen_s(&fp, file_name, "r");
if (fp == NULL) {
printf("Fail to get a correct data sum number!");
exit(1);
}
while (!feof(fp)) {
tmp = fgetc(fp);
if (tmp == '\n')
num++;
}
//fgetc(fp) && num++;
printf("%s: %d charaters in the file\n", file_name, num);
fclose(fp);
return num;
}
4. 字符串切割
// String Split
vector<string> split(const string &str, const string &pattern)
{
//const char* convert to char*
char * strc = new char[strlen(str.c_str()) + 1];
strcpy(strc, str.c_str());
vector<string> resultVec;
char* tmpStr = strtok(strc, pattern.c_str());
while (tmpStr != NULL)
{
resultVec.push_back(std::string(tmpStr));
tmpStr = strtok(NULL, pattern.c_str());
}
delete[] strc;
return resultVec;
};
5. 按行读取txt文件,通过字符串切割定位目标并保存到新文件。
// Read txt by line
int read_txt_lines(const char* path, const char* dst_path)
{
ifstream ifs(path);
ofstream ofs(dst_path);
string line;
int rows = 0;
while (getline(ifs, line))
{
vector<string>str_vector;
str_vector = split(line, ",");
if (!str_vector.empty()) {
ofs << str_vector[0] << '\n';
rows++;
}
}
ifs.close();
ofs.close();
return rows;
}