C++ 新建一個.txt文件 && 新建一個文件夾

一、新建一個.txt文件

1、找到路徑(可執行文件所在的目錄)

CString ReturnPath()  
{
    CString sPath;
    // GetModuleFileName():獲取當前進程已加載模塊的文件的完整路徑,該模塊必須由當前進程加載。
    GetModuleFileName(NULL, sPath.GetBufferSetLength(MAX_PATH+1), MAX_PATH);   
    sPath.ReleaseBuffer();
    int nPos;
    nPos=sPath.ReverseFind('\\');
    sPath=sPath.Left(nPos);
    return sPath;
}

2、定義文件想要放置的路徑(CString格式)

#include <atlstr.h>
#include <time.h>
#include <tchar.h>

#define TXT_FILE	ReturnPath() + _T("\\message.txt")	

3、創建txt文件

//打開txt文件
/**
* GENERIC_READ 表示允許對設備進行讀訪問;
* 如果爲 GENERIC_WRITE 表示允許對設備進行寫訪問
* FILE_SHARE_READ隨後打開操作對象會成功只有請求讀訪問的權限
* OPEN_ALWAYS 如文件不存在則創建它
* FILE_ATTRIBUTE_NORMAL 默認屬性
**/
HANDLE m_hFile = ::CreateFile(TXT_FILE, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(m_hFile==INVALID_HANDLE_VALUE)
        //創建失敗

//在一個文件中設置當前的讀寫位置 —— 移動到文件末尾
/** 
* FILE_BEGIN lOffset將新位置設爲從文件起始處開始算的起的一個偏移
* FILE_CURRENT lOffset將新位置設爲從當前位置開始計算的一個偏移
* FILE_END lOffset將新位置設爲從文件尾開始計算的一個偏移
**/
::SetFilePointer(m_hFile, 0, 0, FILE_END);

4、打印內容

//打印當前時間
TCHAR szCurrentDateTime[64];     
time_t nowtime;     
struct tm ptm;     
time(&nowtime);     
localtime_s(&ptm, &nowtime);    

// strMessage爲內容(CString || LPCTSTR || TCHAR 格式等)
DWORD dWritedBytes = (DWORD)wcslen(strMessage);
#ifdef UNICODE
    swprintf_s(szCurrentDateTime, L"[%.2d-%.2d-%.2d %.2d:%.2d:%.2d]  ",     
    ptm.tm_year + 1900, ptm.tm_mon + 1, ptm.tm_mday,     
    ptm.tm_hour, ptm.tm_min, ptm.tm_sec); 

    // 轉格式,否則會是亂碼
    DWORD a=0xFEFF; 
    ::WriteFile(m_hFile, &a, sizeof(a), &dWritedBytes, NULL); 
    ::WriteFile(m_hFile, szCurrentDateTime, (DWORD)wcslen(szCurrentDateTime)*sizeof(TCHAR), &dWritedBytes, NULL);
    ::WriteFile(m_hFile, strMessage, (DWORD)wcslen(strMessage)*sizeof(TCHAR), &dWritedBytes, NULL);
    ::WriteFile(m_hFile, L"\r\n", 2*sizeof(TCHAR), &dWritedBytes, NULL);

#else
    sprintf_s(szCurrentDateTime, "[%.2d-%.2d-%.2d %.2d:%.2d:%.2d]	",     
    ptm.tm_year + 1900, ptm.tm_mon + 1, ptm.tm_mday,     
    ptm.tm_hour, ptm.tm_min, ptm.tm_sec); 

    ::WriteFile(m_hFile, szCurrentDateTime, (DWORD)wcslen(szCurrentDateTime), &dWritedBytes, NULL);
    ::WriteFile(m_hFile, strMessage, (DWORD)strlen(strMessage), &dWritedBytes, NULL);
    ::WriteFile(m_hFile, "\r\n", 2, &dWritedBytes, NULL);
#endif

// 針對指定的文件句柄,刷新內部文件緩衝區 
::FlushFileBuffers(m_hFile);

5、關閉文件句柄

//關閉文件
::CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;

二、新建一個文件夾

1、頭文件(Visual Studio 2012)

#include <io.h>
#include <direct.h>

2、定義路徑

// CDataUtils::W2S():自己寫的格式轉化函數,CString格式轉std::string格式
#define EXCEL_FILE	CDataUtils::W2S(ReturnPath()+ _T("\\EXCEL REPORT\\"))

3、創建文件夾

//創建EXCEL REPORT文件夾
if (0 != ::_access(EXCEL_FILE.c_str(), 0))
{
      // if this folder not exist, create a new one.
      ::_mkdir(EXCEL_FILE.c_str()); 
}

詳細教程:參見https://www.cnblogs.com/haiyang21/p/9200993.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章