一、txt文件读写
1、写入文件
ofstream f1("index.txt");//创建文件,并写入
f1<<"姓名:"<<"hjimce"<<endl;
f1<<"家庭地址:"<<"福建厦门"<<endl;
f1.close();
2、读取文件
#include <iostream>
#include <fstream> //文件输入输出流
#include <sstream>
vector<vec2> CFeatureReuseDoc::read_mesh2d()
{
vector<vec2>mesh2dvs;
using std::getline;
using std::string;
std::ifstream file("example.txt");
string line;
int ibugId = 1;
while (getline(file, line))
{
std::stringstream lineStream(line);
vec2 landmarkA;
vec2 landmarkB;
vec2 landmarkC;
if (!(lineStream>>landmarkA[0] >> landmarkA[1]>> landmarkB[0] >> landmarkB[1]>> landmarkC[0] >> landmarkC[1])) {
throw std::runtime_error(string("Landmark format error while parsing the line: " + line));
}
mesh2dvs.push_back(landmarkA);
mesh2dvs.push_back(landmarkB);
mesh2dvs.push_back(landmarkC);
++ibugId;
}
return mesh2dvs;
}
二、cstring、string
1、ctring转string:
CString file = lpszPathName;
string path=file.GetBuffer(0);
2、ctring转wchar*
CString strFoo =fileDialog.GetPathName();
WCHAR wstr[256];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, strFoo.GetBuffer(0), -1, wstr, 256);
3、string 转wchar*
string strFoo =m_imagefilepathname.back();
const char* szName = strFoo.c_str();
m_imagefilepathname.pop_back();
WCHAR wstr[1000];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szName, -1, wstr, 1000);
4、 int 类型转string
. stringstream( )
<sstream.h>
例如:
int hello=4;
stringstream ss;
ss<<hello;
string s=ss.str();
//调用string的方法
cout<<s.c_str()<<endl;
5、string 到char*转换
string filename;
const char* c=filename.c_str();
三、文件夹下面目录搜索
//文件夹下指定类型目录搜索
/*调用示例:
vector<string>filepathname;
ScanDirectory(filesrc,".txt",filepathname);//filesrc是文件夹名字
*/
#include <string>
#include <io.h>
bool CFeatureReuseDoc::ScanDirectory( const string &src_dir_path,const const string &file_extension,vector<string>& src_files)
{
if (-1==_access( src_dir_path.c_str() ,0) )
{
return false;
}
_finddata_t fileInfo;
intptr_t hFile;
string dirName_filter = src_dir_path + string("\\") + string("*.*");
if ( ( hFile = _findfirst( dirName_filter.c_str(), &fileInfo ) ) != -1 )
{
do
{
if ( !(fileInfo.attrib & _A_SUBDIR) )
{
if ( file_extension == string(".*") || getFileType(fileInfo.name)== file_extension )
{
string filename = src_dir_path + string("\\") + string(fileInfo.name);
src_files.push_back(filename);
}
}
} while (_findnext(hFile,&fileInfo) == 0);
_findclose(hFile);
}
return true;
}
const string CFeatureReuseDoc::getFileType( const string &filename )
{
string::size_type pos = filename.find_last_of( '.' );
if ( pos != string::npos )
{
return string( filename, pos, string::npos );
}
else
{
// return null string
return "";
}
}