源代码如下:
//
// 通过CreateFile创建一个MyFile.txt的文本文件
//
// 通过WriteFile将一系列字符串写入到MyFile.txt文本文件中
//
//
#include <iostream>
#include <cstdio>
#include <cwindow.h>
using namespace std;
void Create_Write_file();
void main()
{
Create_Write_file();
cout<<"\n\n主程序结束\n"<<endl;
}
void Create_Write_file()
{
HANDLE hFile;
hFile=CreateFile("MyFile.txt",
GENERIC_WRITE|GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_READONLY,
NULL);
if(hFile==INVALID_HANDLE_VALUE)
{
OutputDebugString("Create File is False");//调试的时候能输出到输出窗口
printf("Create File is False");// 这个用于输出到屏幕
}
const int BUFSIZE=4096*7;
char chBuffer[BUFSIZE];
char *p;
p=chBuffer;
for(int i=0;i<10000;i++)
{
if(i%2==0)
{
memcpy(p,"Test",4);
p=p+4;}
else
{
memcpy(p," ",4);
p=p+1;
}
}
DWORD dwWriteSize=0;
BOOL bRet;
bRet=WriteFile(hFile,chBuffer,25000,&dwWriteSize,NULL);
if(bRet)
{
OutputDebugString("Write File is True");
printf("Write File is True");
}
FlushFileBuffers(hFile);
}
得到的结果如下图所示: