说明
模板类实现Txt文件的读写,使用时应注意h和cpp文件放在同一目录下但cpp不要加入工程中才能使用。
程序
//CTxtT.h
#pragma once
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include "CDebug.h"
#include "CSprintf.h"
using namespace std;
template <class T>
class CTxtT
{
public:CTxtT(string name);
void modifyName(string name);
~CTxT() { }
vector<vector<T>> read();
bool write(vector<vector<T>> vec);
private:
string name;
};
#include "CTxtT.cpp"
//CTxtT.cpp
#include "pch.h"
#include "CTxtT.h"
template<class T>
CTxtT<T>::CTxtT(string name)
{
this->name = name;
}
template<class T>
void CTxtT<T>::modifyName(string name)
{
this->name = name;
}
template<class T>
vector<vector<T>> CTxtT<T>::read()
{
ifstream myfile(name.c_str());
if (!myfile.is_open())
{
OutputDebugString(_T("can not open this file"));
return { };
}
int w, h;
myfile >> w >> h;
vector<vector<T>> vec;
vec.resize(w);
for (int i = 0; i < w; i++)
{
vec[i].resize(h);
}
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
myfile >> vec[i][j];
}
}
return vec;
}
template<class T>
bool CTxtT<T>::write(vector<vector<T>> vec)
{
if (vec.empty()) //空的,不做任何处理
return false;
if (name.empty())
return false;
unsigned int w = vec.size();
unsigned int h = vec[0].size();
ofstream outfile(name.c_str());
if (!outfile.is_open())
return false;
outfile.clear();
outfile << w << " " << h << "\n";
for (unsigned int i = 0; i < w; i++)
{
for (unsigned int j = 0; j < h; j++)
{
outfile << vec[i][j];
if (j != h - 1)
outfile << " ";
}
outfile << "\n";
}
outfile.close();
return true;
}