常用代码段

1.获取当前程序工作目录

//使用string  
char exeFullPath[MAX_PATH]; 
::GetModuleFileName(NULL,exeFullPath,MAX_PATH);    
m_Dir=exeFullPath;
m_Dir=m_Dir.substr(0,m_Dir.find_last_of('\\')+1);

 

//使用CString
TCHAR exeFullPath[MAX_PATH]; 
::GetModuleFileName(NULL,exeFullPath,MAX_PATH);    
CString m_modelFileName=exeFullPath;
m_modelFileName=m_modelFileName.Left(m_modelFileName.ReverseFind(_T('\\'))+1);

  

2.判断文件是否存在

使用时要包含头文件(#include "io.h"):

int _access(  const char *path, int mode );
int _waccess(  const wchar_t *path,   int mode );

int _taccess(  const TCHAR *path, int mode );
方法返回:如果满足模式要求则返回0,否则返回-1 

mode值      检查文件内容

00      存在
02      可写入

04     可读取

06     可读取和写入

MSDN示例:

#include  <io.h>
#include  <stdio.h>
#include  <stdlib.h>

int main( void )
{
    // Check for existence.
    if( (_taccess( "crt_ACCESS.C"0 )) != -1 )
    {
        printf_s( "File crt_ACCESS.C exists.\n" );
        // Check for write permission.
        
// Assume file is read-only.
        if( (_taccess( "crt_ACCESS.C"2 )) == -1 )
            printf_s( "File crt_ACCESS.C does not have write permission.\n" );
    }
}

 

 

3.字符串转换成数值函数

//字符串转换成小数
double _tcstod(TCHAR* nptr,TCHAR** endPtr)

//字符串转换成长整型
long  _tcstol(TCHAR* nptr,TCHAR** endPtr,int base

//字符串转换成无符号长整型
unsigned long _tcstoul(TCHAR* nptr,TCHAR** endPtr,int base

 nptr:要转换的字符串指针

endPtr:扫描结事的字符串位置

base:字符串表示的进制形式,可以为2,8,10,16

 

//字符串转换成整形
int _ttoi(const char *str);
//字符串转换成长整形
long _ttol(const char *str);
//字符串转换成小数数值
double _ttof(const char *str);

 

 4.char* 与w_char*相互转换

 

#include <atlconv.h>
 
// 要转换的指针
char* m_char;
w_char* m_wchar;

//char*-->w_char*
USES_CONVERSION;
m_wchar=A2W(m_char);

//w_char*-->char*
USES_CONVERSION;
m_char=W2A(m_wchar);

 

 

 

posted on 2011-09-23 10:36  钱廷柱  阅读(336)  评论(0编辑  收藏  举报

导航