zoukankan      html  css  js  c++  java
  • Windows API初练手 -- 疯狂写文件代码

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


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


    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] = "";        //文件路径配置
    	char stuff_str[255] = "";   //文件写入内容
    	char fileName[255] = "";    //文件名
    	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] = "";
    	char fileName[255] = "";
    	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
    ",path);
    		fp = fopen(path,"w+");
    		fwrite(stuff_str,sizeof(stuff_str),1,fp);
    		memset(path,0x00,255);
    	}
    	fclose(fp);
    	return 0;
    }


  • 相关阅读:
    java学习——内部类、匿名内部类
    Java中接口之间的继承
    Settings
    POM
    Maven指令
    Maven生命周期
    内部类
    Modules
    Simple Maven Project
    Maven概述
  • 原文地址:https://www.cnblogs.com/csnd/p/12897053.html
Copyright © 2011-2022 走看看