FILE.h
#pragma once
#include <io.h>
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include <sstream>
using namespace std;
class File_Operation {
public:
File_Operation();
//读txt的数据
void read_txt_double(string file, vector<vector<double>>& data);
//得到文件夹下文件
void getFiles(string path, vector<string>& files);
//保存txt数据
void saveFiles_txt(string path, vector<vector<double>> data);
};
FILE.cpp
#include "file_operation.h"
using namespace std;
File_Operation::File_Operation() {}
void File_Operation::read_txt_double(string file, vector<vector<double>> &data) {
ifstream in(file);
string line;
int i = 0, j = 0;
stringstream str;
while (getline(in, line)) {//每一次获取一行的数据到line
stringstream ss(line);//初始化ss数据为line
double x;
vector<double> point;
while (ss >> x) {
point.push_back(x);
}
data.push_back(point);
i++;
}
//return data;
}
void File_Operation::getFiles(string path, vector<string>& files) {
//"C:/Users/12875/Desktop/数据/";
//文件句柄
intptr_t hFile = 0;
//文件信息,声明一个存储文件信息的结构体
struct _finddata_t fileinfo;
string p; //字符串,存放路径
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)//若查找成功,则进入
{
do
{
//如果是目录,迭代之(即文件夹内还有文件夹)
if ((fileinfo.attrib & _A_SUBDIR))
{
//文件名不等于"."&&文件名不等于".."
//.表示当前目录
//..表示当前目录的父目录
//判断时,两者都要忽略,不然就无限递归跳不出去了!
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("/").append(fileinfo.name), files);
}
//如果不是,加入列表
else
{
files.push_back(p.assign(path).append("/").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
//_findclose函数结束查找
_findclose(hFile);
}
}
void File_Operation::saveFiles_txt(string path,vector<vector<double>> data) {
///ofstream out(path);
ofstream outfile(path);
// cout << path << endl;
//cout << data.size() << endl;
//outfile << "hello world!" << "," << "0" << endl;
//outfile.close();
// if (outfile.is_open())
{
for (int i = 0; i < data.size(); i++) {
int n = data[i].size();
for (int j = 0; j < n; j++) {
outfile << data[i][j];
outfile << ((j + 1 < n) ? " " : "\n");
}
}
}
//system("pause");
}