1 C++
//部分数据如下:
-0.977426 -2.15014 -1.30423 0.294882 0.946758 -0.129203 27 40 14
-0.961579 -2.15944 -1.30909 -0.150544 0.986361 0.066552 22 23 22
-0.921011 -2.15342 -1.30418 -0.0309735 0.98117 0.190644 17 17 22
-0.82167 -2.16392 -1.30542 0.0566997 0.987977 -0.143831 25 38 20
-0.786859 -2.16086 -1.3014 -0.110363 0.984852 0.133738 37 42 28
将数据读取到Vector数组中
// fread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
// read1 采用fread函数,按字符分配到vector数组
// read2 getline按行读取数据,按字符分配到vector数组
// read3 getline按行读取数据,按字符串分配到vector
// read4 fin按行读取数据,按字符串分配到vector
// read5 采用fread函数,按字符串分配到vector
#include "pch.h"
#include <iostream>
#include<vector>
#include <stdio.h>
#include <stdlib.h>
#include<ctime>
#include<fstream>
#include<string>
#include<sstream>
#include<cassert>
using namespace std;
double str2num(const string str)
{
stringstream ss(str);
double num;
ss >> num;
return num;
}
struct Point
{
double x;
double y;
double z;
};
vector<Point> read1(const char * file)
{
FILE* pFile; //文件指针
long lSize; // 用于文件长度
char* buffer; // 文件缓冲区指针
size_t result; // 返回值是读取的内容数量
vector<string> v;
pFile = fopen(file, "rb");
if (pFile == NULL) { fputs("File error", stderr); exit(1); } // 如果文件错误,退出1
// obtain file size: 获得文件大小
fseek(pFile, 0, SEEK_END); // 指针移到文件末位
lSize = ftell(pFile); // 获得文件长度
rewind(pFile); // 函数rewind()把文件指针移到由stream(流)指定的开始处, 同时清除和流相关的错误和EOF标记
// allocate memory to contain the whole file: 为整个文件分配内存缓冲区
buffer = (char*)malloc(sizeof(char) * lSize); // 分配缓冲区,按前面的 lSize
if (buffer == NULL) { fputs("Memory error", stderr); exit(2); } // 内存分配错误,退出2
// copy the file into the buffer: 该文件复制到缓冲区
result = fread(buffer, 1, lSize, pFile); // 返回值是读取的内容数量
if (result != lSize) { fputs("Reading error", stderr); exit(3); } // 返回值如果不和文件大小,读错误
/* the whole file is now loaded in the memory buffer. */ //现在整个文件载入内存缓冲区
// 读到内存,看自己怎么使用了...............
// ...........
//cout << buffer;
v.push_back(buffer);
cout << "文件大小: " << v[0].size() << endl;
vector<Point>num;
int i = 0;
while (i < v[0].size())
{
Point p;
string num_s = "";
while (v[0][i] != ' ')
{
num_s += v[0][i];
i++;
}
p.x = str2num(num_s);
i++;
num_s = "";
while (v[0][i] != ' ')
{
num_s += v[0][i];
i++;
}
p.y = str2num(num_s);
i++;
num_s = "";
while (v[0][i] != ' ')
{
num_s += v[0][i];
i++;
}
p.z = str2num(num_s);
num.push_back(p);
while ((v[0][i] != '\n') && (i < v[0].size()))
{
i++;
}
i++;
}
// terminate // 文件终止
fclose(pFile);
free(buffer);
}
vector<Point> readTxt2(string file)
{
std::cout << "读取数据中..." << endl;
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
string s;
//char str;
vector<string> ve;
vector<Point> num;
while (getline(infile, s))
{
Point p;
int i = 0;
string num_s = "";
while (s[i] != ' ')
{
num_s += s[i];
i++;
}
p.x = str2num(num_s);
i++;
num_s = "";
while (s[i] != ' ')
{
num_s += s[i];
i