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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值