文件批量处理
朋友让帮忙写一个文件处理的软件。
花了一天时间基本写好,最后卡在一个栈溢出问题。写贴出代码。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <windows.h> #include <tchar.h> #pragma warning(disable:4996) #define N 39 void color(const unsigned short color1) { if (color1 >= 0 && color1 <= 15) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color1); else SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15); } int main(void) { system("title 文件整理"); char ch; bool cat; int n = 0, b = 0; for (; n < 9999; n++, b++) {//循环,一次处理一个 char arr[N] = { 0 }, size = sizeof(char), buf[20] = { 0 }; FILE *fp; char astr[20] = "D:\\REED\\O000";//读取文件的路径 if(b > 9 && b < 100) { strcpy(astr, "D:\\REED\\O00"); } else if(b > 99 && b < 1000) { strcpy(astr, "D:\\REED\\O0"); } else if(b > 999 && b < 10000) { strcpy(astr, "D:\\REED\\O"); } char bstr[8] = { 0 }; char mstr[15] = { 0 }; char mbuf[45] = "move"; itoa(b, bstr, 10);//将整型转换为字符串 strcat(astr, bstr);//完善打开文件路径 if ((fp = fopen(astr, "rb+")) == NULL) {//打开文件 color(4); printf("%s 文件打开出错\n请检查文件是否存在!\n", astr); color(15); system("PAUSE"); continue; } fread(arr, size, N, fp);//读取文件数据 fseek(fp, 8, SEEK_SET);//移动指针到指定位置 for (int n = 0; (ch = fgetc(fp)) != ')'; ++n) {//循环 if (ch == '\\' || ch == '/' || ch == ' ')//替换非规定符号 ch = '_'; mstr[n] = ch; } std::string dirName = mstr;//文件夹名称 bool flag = CreateDirectory(dirName.c_str(), NULL);//创建文件夹 fclose(fp);//关闭流 //char mbuf[45] = "move"; strcat(mbuf, " ");//cmd命令 strcat(mbuf, astr); strcat(mbuf, " "); strcat(mbuf, "D:\\Ubuntu\\"); strcat(mbuf, mstr); system(mbuf); color(2); printf("整理完成!\n"); color(15); } printf("文件整理完毕!按任意键结束程序!\n"); system("PAUSE"); return 0; }
刚开始,定义mbuf的字符数组在被注释代码的位置,但是调试时执行错误:Program received signal SIGSEGV,Segmentation fault.”,查询后得知为栈溢出。
下面是借鉴的一些文件:
在使用WINAPI参数时发生 cannot convert 'char*' to 'LPCWSTR {aka const wchar类似问题,借鉴:
Copyfile,MoveFile函数报错,前者5,后者183,无权限。