VC获取系统临时文件夹temp

来源:互联网 发布:js弹窗按键 编辑:程序博客网 时间:2024/06/07 18:27

MSDN:创建和使用一个临时文件

一、介绍

系统临时文件夹可用%tmp%或者%temp%查看,路径为C:\Users\pc\AppData\Local\Temp
获取临时文件夹路径GetTempPath, GetTempFileName获取临时文件夹下文件名

二、案例

这个应用程序打开一个文件指定的用户,并使用一个临时文件将文件转换为大写字母。注意,给定的源文件被认为是一个ASCII文本文件和创建的新文件覆盖每次运行应用程序。
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "Windows.h"/* int main(){HANDLE hFile = CreateFile(TEXT("text.txt"), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);if (hFile == INVALID_HANDLE_VALUE){//MessageBox(TEXT("创建文件失败!"));return 1;}LARGE_INTEGER liDistanceToMove;liDistanceToMove.QuadPart = 102400000; //设置成这个大,单位字节if (!SetFilePointerEx(hFile, liDistanceToMove, NULL, FILE_BEGIN)){//MessageBox(TEXT("移动文件指针失败!"));}if (!SetEndOfFile(hFile)){//MessageBox(TEXT("设置文件尾失败!"));}CloseHandle(hFile);    return 0;}*/#include <windows.h>#include <tchar.h>#include <stdio.h>#define BUFSIZE 1024void PrintError(LPCTSTR errDesc);int _tmain(int argc, TCHAR *argv[]){HANDLE hFile = INVALID_HANDLE_VALUE;HANDLE hTempFile = INVALID_HANDLE_VALUE;BOOL fSuccess = FALSE;DWORD dwRetVal = 0;UINT uRetVal = 0;DWORD dwBytesRead = 0;DWORD dwBytesWritten = 0;TCHAR szTempFileName[MAX_PATH];TCHAR lpTempPathBuffer[MAX_PATH];char  chBuffer[BUFSIZE];LPCTSTR errMsg;if (argc != 2){_tprintf(TEXT("Usage: %s <file>\n"), argv[0]);return -1;}//  Opens the existing file. hFile = CreateFile(argv[1],               // file name GENERIC_READ,          // open for reading 0,                     // do not share NULL,                  // default security OPEN_EXISTING,         // existing file only FILE_ATTRIBUTE_NORMAL, // normal file NULL);                 // no template if (hFile == INVALID_HANDLE_VALUE){PrintError(TEXT("First CreateFile failed"));return (1);}//  Gets the temp path env string (no guarantee it's a valid path).dwRetVal = GetTempPath(MAX_PATH,          // length of the bufferlpTempPathBuffer); // buffer for path if (dwRetVal > MAX_PATH || (dwRetVal == 0)){PrintError(TEXT("GetTempPath failed"));if (!CloseHandle(hFile)){PrintError(TEXT("CloseHandle(hFile) failed"));return (7);}return (2);}_tprintf(TEXT("  %s\n"), lpTempPathBuffer);//  Generates a temporary file name. uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp filesTEXT("DEMO"),     // temp file name prefix 0,                // create unique name szTempFileName);  // buffer for name _tprintf(TEXT("  %s\n"), szTempFileName);if (uRetVal == 0){PrintError(TEXT("GetTempFileName failed"));if (!CloseHandle(hFile)){PrintError(TEXT("CloseHandle(hFile) failed"));return (7);}return (3);}//  Creates the new file to write to for the upper-case version.hTempFile = CreateFile((LPTSTR)szTempFileName, // file name GENERIC_WRITE,        // open for write 0,                    // do not share NULL,                 // default security CREATE_ALWAYS,        // overwrite existingFILE_ATTRIBUTE_NORMAL,// normal file NULL);                // no template if (hTempFile == INVALID_HANDLE_VALUE){PrintError(TEXT("Second CreateFile failed"));if (!CloseHandle(hFile)){PrintError(TEXT("CloseHandle(hFile) failed"));return (7);}return (4);}//  Reads BUFSIZE blocks to the buffer and converts all characters in //  the buffer to upper case, then writes the buffer to the temporary //  file. do{if (ReadFile(hFile, chBuffer, BUFSIZE, &dwBytesRead, NULL)){//  Replaces lower case letters with upper case//  in place (using the same buffer). The return//  value is the number of replacements performed,//  which we aren't interested in for this demo.CharUpperBuffA(chBuffer, dwBytesRead);fSuccess = WriteFile(hTempFile,chBuffer,dwBytesRead,&dwBytesWritten,NULL);if (!fSuccess){PrintError(TEXT("WriteFile failed"));return (5);}}else{PrintError(TEXT("ReadFile failed"));return (6);}//  Continues until the whole file is processed.} while (dwBytesRead == BUFSIZE);//  The handles to the files are no longer needed, so//  they are closed prior to moving the new file.if (!CloseHandle(hFile)){PrintError(TEXT("CloseHandle(hFile) failed"));return (7);}if (!CloseHandle(hTempFile)){PrintError(TEXT("CloseHandle(hTempFile) failed"));return (8);}//  Moves the temporary file to the new text file, allowing for differnt//  drive letters or volume names.fSuccess = MoveFileEx(szTempFileName,TEXT("AllCaps.txt"),MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);if (!fSuccess){PrintError(TEXT("MoveFileEx failed"));return (9);}else_tprintf(TEXT("All-caps version of %s written to AllCaps.txt\n"), argv[1]);return (0);}//  ErrorMessage support function.//  Retrieves the system error message for the GetLastError() code.//  Note: caller must use LocalFree() on the returned LPCTSTR buffer.LPCTSTR ErrorMessage(DWORD error){LPVOID lpMsgBuf;FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER| FORMAT_MESSAGE_FROM_SYSTEM| FORMAT_MESSAGE_IGNORE_INSERTS,NULL,error,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf,0,NULL);return((LPCTSTR)lpMsgBuf);}//  PrintError support function.//  Simple wrapper function for error output.void PrintError(LPCTSTR errDesc){LPCTSTR errMsg = ErrorMessage(GetLastError());_tprintf(TEXT("\n** ERROR ** %s: %s\n"), errDesc, errMsg);LocalFree((LPVOID)errMsg);}

原创粉丝点击