Windows API初练手 -- 疯狂写文件代码

时间:2023-03-09 09:37:58
Windows API初练手 -- 疯狂写文件代码

警告:恶作剧软件,慎用!仅供初学者研究代码所用!!!

提示:默认文件创建目录在"D:\test",如果需要使用的话请自行更改目录。

1. Windows API 版本 (调用系统函数,速度较快)

#include <cstdio>
#include <cstdlib>
#include <windows.h>
#include <iostream>
#include <string.h> using namespace std; #define CREATE_FILE_NUM 5 #pragma comment(lib,"ws2_32") int main(void)
{
char path[255] = "\0"; //文件路径配置
char stuff_str[255] = "\0"; //文件写入内容
char fileName[255] = "\0"; //文件名
HANDLE hfile = NULL; //文件句柄
DWORD count; //记录写入函数返回的成功字符数
strcat(stuff_str,"------PeterZheng------");
for (int i = 0 ; i < CREATE_FILE_NUM ; i++)
{
memset(path,0x00,255);
memset(fileName,0x00,255);
strcat(path,"D:\\test"); //文件填充目录
wsprintf(fileName,"\\%d.txt",i);
strcat(path,fileName);
hfile = CreateFile(path,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); //打开文件
if (hfile == INVALID_HANDLE_VALUE) //异常处理
{
continue;
}
WriteFile(hfile,&stuff_str,sizeof(stuff_str),&count,NULL); //写文件
CloseHandle(hfile); //关句柄
}
printf("OK");
return 0;
}

2. C语言内部函数版本(c语言内部对系统函数做了封装,调用简单,但速度相对较慢,功能较少)

#include <cstdio>
#include <cstdlib>
#include <windows.h>
#include <iostream>
#include <string.h> using namespace std; #define CREATE_FILE_NUM 5 #pragma comment(lib,"ws2_32") int main(void)
{
int count = 0;
FILE *fp = NULL;
char path[255] = "\0";
char fileName[255] = "\0";
char stuff_str[255] = "------PeterZheng------";
for (int i = 0 ; i < CREATE_FILE_NUM ; i++)
{
strcat(path,"D:\\test\\");
wsprintf(fileName,"%d.txt",i);
strcat(path,fileName);
printf("%s\n",path);
fp = fopen(path,"w+");
fwrite(stuff_str,sizeof(stuff_str),1,fp);
memset(path,0x00,255);
}
fclose(fp);
return 0;
}