2008-7-16 7:48:03 喝小酒的网摘
 
用C++遍历文件夹并加密文件
将一个任意类型的文件,包括整个文件夹,按一定的长度逐段逐段地读进内存,然后从内存写入磁盘,做成文件加密,即读一段入内存,然后加密了之后将密文写入磁盘

源码如下:

//#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <conio.h>

#define MAXSTRLEN 512
using namespace std;

void read_copy_file(char *pathfile)
{
    FILE* fd;
    FILE* fp;
    char buf[MAXSTRLEN+1];
    int readlen, writelen = 0;
   
    memset(buf,0,MAXSTRLEN+1);
    fd=fopen(pathfile,"rb");
    fp=fopen(strcat(pathfile,"_bak"),"wb");
    fseek(fd,0,SEEK_SET);
    fseek(fp,0,SEEK_SET);
    while((readlen = fread(buf, sizeof(char), MAXSTRLEN, fd)) != 0)
    {
        // 写入的字节数改为readlen,即读取到的字节数
        writelen += fwrite(buf, sizeof(char), readlen, fp);
        memset(buf, 0, MAXSTRLEN+1);
    }
    cout << writelen << " bytes written." << endl<<endl;
    fclose(fd);
    fclose(fp);
}

BOOL IsRoot(LPCTSTR lpszPath)
{
    TCHAR szRoot[4];
    wsprintf(szRoot, "%c:\\", lpszPath[0]);
    return (lstrcmp(szRoot, lpszPath) == 0);
}

void FindInAll(::LPCTSTR lpszPath)
{
    TCHAR szFind[MAX_PATH];
    lstrcpy(szFind, lpszPath);
    if (!IsRoot(szFind))
        lstrcat(szFind, "\\");
    lstrcat(szFind, "*.*"); // 找所有文件
    WIN32_FIND_DATA wfd;
    HANDLE hFind = FindFirstFile(szFind, &wfd);
    if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
    return;

    do
    {
        if (wfd.cFileName[0] == '.')
            continue; // 过滤这两个目录
        if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            TCHAR szFile[MAX_PATH];
            if(IsRoot(lpszPath))
                wsprintf(szFile, "%s%s", lpszPath, wfd.cFileName);
            else
                wsprintf(szFile, "%s\\%s", lpszPath, wfd.cFileName);
            FindInAll(szFile); // 如果找到的是目录,则进入此目录进行遍历递归
        }
        else
        {
            TCHAR szFile[MAX_PATH];
            if (IsRoot(lpszPath))
                wsprintf(szFile, "%s%s", lpszPath, wfd.cFileName);
            else
                wsprintf(szFile, "%s\\%s", lpszPath, wfd.cFileName);
            printf("%s\n",szFile);
            read_copy_file(szFile);
            // 对文件进行操作
        }
    }
    while (FindNextFile(hFind, &wfd));

    FindClose(hFind); // 关闭查找句柄
}
int main(int argc, char* argv[])
{
    FindInAll("E:\\test"); //这里改成你要遍历的文件夹路径
    getch();
    return 0;
}
[Blog.Const.Net.Cn]