dpt文件片段:
41.38674,0.24518
40.42426,0.25005
39.46177,0.26990
38.49929,0.29840
37.53681,0.32108
36.57433,0.31796
35.61185,0.27035
34.64936,0.16700
33.68688,0.01392
32.72440,-0.12851
31.76192,-0.12658
30.79943,0.02354
29.83695,0.17565
DataProc.h
#pragma once
#include <vector>
using namespace std;
class CDataProc
{
public:
CDataProc();
~CDataProc();
public:
bool readDptFile(const char* In_FilePath, vector<double> &In_X,vector<double> &In_Y);// 从指定dpt文件读取数据
public:
// 去除尾部空格
char *rtrim(char *str);
// 去除头部空格
char *ltrim(char *str);
// 去除首尾空格
char *trim(char *str);
};
DataProc.cpp
#include "stdafx.h"
#include "DataProc.h"
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include <ctype.h>
#pragma warning(disable:4996)
CDataProc::CDataProc()
{
}
CDataProc::~CDataProc()
{
}
// 从指定dpt文件读取数据,读取成功返回true,读取失败返回false
bool CDataProc::readDptFile(const char* In_FilePath, vector<double> &In_X, vector<double> &In_Y)
{
if (In_FilePath == nullptr) {
printf("文件路径为空!\n");
return false;
}
// 判断文件是否存在
if (_access(In_FilePath, 0) == -1) {
printf("文件不存在!\n");
}
In_X.clear();
In_Y.clear();
// 读取文件内容
FILE *fp;
char strLine[256] = {0};
if ((fp = fopen(In_FilePath, "r")) == nullptr) {
printf("fopen error!");
return false;
}
// 读取每一行
while (!feof(fp)) {
memset(strLine, 0, 256);
fgets(strLine, 256, fp);// 读取每一行,带有\n,替换成\0
if (strlen(strLine) > 0)
{
strLine[strlen(strLine) - 1] = '\0';// 带有\n, 替换成\0
printf("%s\n", strLine);// 输出每一行
// 获取逗号分隔数据
char *p = strtok(strLine, ",");
vector<string> strDataArray;
while (p != nullptr) {
strDataArray.push_back(string(p));
p = strtok(NULL, ",");
}
// 前后去除空格
if (strDataArray.size() != 2) {
continue;
}
string str1 = trim(const_cast<char*>(strDataArray[0].c_str()));
string str2 = trim(const_cast<char*>(strDataArray[1].c_str()));
// 转换成double,存入数组中
double d1, d2;
d1 = atof(str1.c_str());
d2 = atof(str2.c_str());
In_X.push_back(d1);
In_Y.push_back(d2);
}
}
fclose(fp);
printf("In_X's size is:%d\n", In_X.size());
return true;
}
// 去除尾部空格
char * CDataProc::rtrim(char *str)
{
if (str == NULL || *str == '\0')
{
return str;
}
int len = strlen(str);
char *p = str + len - 1;
while (p >= str && isspace(*p))
{
*p = '\0';
--p;
}
return str;
}
// 去除头部空格
char * CDataProc::ltrim(char *str)
{
if (str == NULL || *str == '\0')
{
return str;
}
int len = 0;
char *p = str;
while (*p != '\0' && isspace(*p))
{
++p;
++len;
}
memmove(str, p, strlen(str) - len + 1);
return str;
}
// 去除首尾空格
char * CDataProc::trim(char *str)
{
str = rtrim(str);
str = ltrim(str);
return str;
}