c++ 项目实战记录(一) char *、CString 与 string 之间的转换

在Windows系统中,使用VS编程时,有两种字符集:ANSI(使用多字节字符)和 Unicode(使用 Unicode 字符集)。对于相同的环境选择使用不同的字符集,表示的意义不同。

先列举在c/c++中对文件操作的一些函数

//********************************* c++
//****************** Unicode字符集
#define CreateDirectory  CreateDirectoryW /*创建文件夹*/
#define PathIsDirectory  PathIsDirectoryW /*路径是否存在*/
#define DeleteFile  DeleteFileW /*删除文件*/
#define MoveFile  MoveFileW /*移动文件*/

//******************  ANSI节符集
#define CreateDirectory  CreateDirectoryA
#define PathIsDirectory  PathIsDirectoryA
#define DeleteFile  DeleteFileA
#define MoveFile  MoveFileA
//********************************* c
// *************************  
int  _access(char const* _FileName,  int  AccessMode)/*检查路径是否存在*/
int  _mkdir(char const* _Path)/*创建不存在路径*/
int  _remove(const char* path);/*删除文件*/
FILE * fopen(const char* _Filename, const char* _Mode);/*打开文件*/

//   对应的宽字节版本
int  _waccess( const wchar_t* _Filename, int  AccessMode)/**/
int  _wmkdir(const wchar_t* _Path);
int  _wremove(const wchar_t* _Filename);
errno_t  _wfopen_s(FILE ** _File,  const wchar_t* _Filename,  const wchar_t* _Mode);

在实际操作中可能涉及转换转化问题

//*****************string 转 char*
/*计算时间戳*/
time_t curtime = time(0); 
tm tim;   
localtime_s(&tim, &curtime);  
/*string型路径*/
std::string TmpPath =  "D:\\Test";
char path[MAX_PATH];
sprintf_s(path, "%s\\[%02d_%02d_%02d]", obj.TmpPath.c_str(),
		 tim.tm_hour, tim.tm_min, tim.tm_sec);
//****************char* 转 string
//获取项目路径
std::string getResourcePath()
{
	char* projectPath = nullptr;
	projectPath = _getcwd(nullptr, 1);
	string filePath(projectPath);

	return filePath;
}
//****************char*或string 转 CString
/*计算时间戳*/
time_t curtime = time(0); 
tm tim;   
localtime_s(&tim, &curtime);  
/*string型路径*/
std::string TmpPath =  "D:\\Test";
CString str;
str.Format(_T("%s\\[%02d_%02d_%02d]"),TmpPath,
           tim.tm_hour, tim.tm_min, tim.tm_sec);
//****************CString 转 string
CString str =  L"D://Test";
std::string path = std::string(((CStringA)str).GetBuffer());

在此次Demo的实现过程中收获:

  1. 使用_getcwd()获取当前项目所在路径
char* projectPath = nullptr;
	projectPath = _getcwd(nullptr, 1);
  1. 使用C语言中的<time.h>获取当前时间(在线程与进程(1)中会涉及到opencv中获取当前毫秒数的函数)
//参数 年:1900 + tim.tm_year; 月:1+ tim.tm_mon; 日:tim.tm_mday; 时:tim.tm_hour; 分:tim.tm_min; 秒:tim.tm_sec
time_t curtime = time(0); 
tm tim;   
localtime_s(&tim, &curtime);  
  1. CString或string同类型的路径可直接相加
//CString 同类型相加
CString s1 = _T("D://Test");  
CString s2 = _T("son1");
CString message = s1 + L"//" + s2;  

在后续会出一篇曾经做过的有关于循环遍历文件夹的操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值