使用Windows API: CreateFile, WriteFile, ReadFile, CloseHandle
應用程式 -> Windows API -> Windows作業系統
----------------------------------------------------------------------------------------------------------
專案類型: Visual C++ -> Win32 -> Win32主控台應用程式
#include "stdafx.h"
#include <windows.h>
#include <cstdio>
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hFile;
DWORD nBytes;
//寫入檔案
hFile = CreateFile(_T("test.out"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
char msg[] = "寫入測試123...";
if( hFile != INVALID_HANDLE_VALUE)
{
WriteFile(hFile, msg, sizeof(msg)-1, &nBytes, NULL);
CloseHandle(hFile);
}
//-----------------------------------------------------------
// 讀取檔案
hFile = CreateFile(_T("test.out"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL);
if(hFile != INVALID_HANDLE_VALUE )
{
char line[256] = {0};
BOOL bResult;
bResult = ReadFile(hFile, line, sizeof(line), &nBytes, NULL);
if( nBytes !=0)
{
printf("%s\r\n", line);
}
CloseHandle(hFile);
}
scanf("%d");
return 0;
}
原始程式: WriteFileTest
------------------------------------------------------------------------------------------------------------
使用C++標準函式庫, 使用檔案串流fstream操作檔案輸入/輸出
專案類型: Visual C++ -> Win32 -> Win32主控台應用程式
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// 寫入檔案
ofstream out("test.out");
out << "標準函式庫寫入檔案";
out.close();
// 讀取檔案
ifstream in("test.out");
char line[256];
in.getline(line, 256);
cout << line << endl;
system("pause");
return 0;
}
原始程式:WriteFileStdCpp
----------------------------------------------------------------------------------------------------
專案類型: Visual C++ -> Win32 -> Win32主控台應用程式
請記得勾選 MFC(參考下圖)
Application EXE -> MFC -> Windows API -> Windows作業系統
留言列表