你解释一下这若干个.txt文件的数据是怎么从一个.out文件生成的?我看到第一个.txt文件的数据,第一栏的可以.out中找到,但第二栏的那些不知从哪里来。而且这个文档的构造跟原先的1.out不同,可见你的真实需求是可变的。
[ 本帖最后由 TonyDeng 于 2014-7-14 20:05 编辑 ]
程序代码:
#include <Windows.h>
#include <cstdio>
#include <cstdlib>
#include <conio.h>
bool OpenSourceFile(FILE** file, const char* path, const char* name);
bool CreateTargetFile(FILE** file, const char* path, size_t count);
HLOCAL GetErrorMessage(DWORD error_code);
void Pause(void);
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf_s("程序使用格式: %s \"数据文件所在路径\"\n", strrchr(argv[0], '\\') + 1);
Pause();
return EXIT_SUCCESS;
}
//const char* dataPath = "..\\open circuit\\";
const char* dataPath = argv[1];
const char* flagString = " TIME V";
printf_s("处理路径: %s\n", dataPath);
FILE* inputFile;
if (!OpenSourceFile(&inputFile, dataPath, "data.out"))
{
Pause();
exit(EXIT_FAILURE);
}
char buffer[1024];
size_t count = 0;
while (fgets(buffer, sizeof(buffer) - 1, inputFile) != NULL)
{
if (strstr(buffer, flagString) != NULL)
{
++count;
FILE* outputFile;
if (!CreateTargetFile(&outputFile, dataPath, count))
{
Pause();
exit(EXIT_FAILURE);
break;
}
printf_s("正在生成输出文件: %d.txt\n", count);
bool escape = false;
while ((fgets(buffer, sizeof(buffer) - 1, inputFile) != NULL) && !escape)
{
if (strlen(buffer) > 0)
{
if (buffer[0] == 0x0c)
{
escape = true;
break;
}
fprintf_s(outputFile, "%s", buffer);
}
}
fclose(outputFile);
}
}
fclose(inputFile);
Pause();
return EXIT_SUCCESS;
}
bool OpenSourceFile(FILE** file, const char* path, const char* name)
{
char fullFilePath[MAX_PATH];
bool success = true;
strcpy_s(fullFilePath, MAX_PATH - 1, path);
strcat_s(fullFilePath, MAX_PATH - 1, name);
if (fopen_s(file, fullFilePath, "rt") != 0)
{
HLOCAL errorMessage = GetErrorMessage(GetLastError());
printf_s("文件\"%s\"打开失败: %s\n", fullFilePath, errorMessage);
LocalFree(errorMessage);
success = false;
}
return success;
}
bool CreateTargetFile(FILE** file, const char* path, size_t count)
{
char fullFilePath[MAX_PATH];
char numberString[4];
bool success = true;
strcpy_s(fullFilePath, MAX_PATH - 1, path);
_itoa_s(count, numberString, sizeof(numberString), 10);
strcat_s(fullFilePath, MAX_PATH - 1, numberString);
strcat_s(fullFilePath, MAX_PATH - 1, ".txt");
if (fopen_s(file, fullFilePath, "wt") != 0)
{
HLOCAL errorMessage = GetErrorMessage(GetLastError());
printf_s("文件\"%s\"创建失败: %s\n", fullFilePath, errorMessage);
LocalFree(errorMessage);
success = false;
}
return success;
}
HLOCAL GetErrorMessage(DWORD errorCode)
{
HLOCAL messageText = NULL;
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageText, 0, NULL);
return messageText;
}
void Pause(void)
{
printf_s("\nPress any key to continue...");
_getch();
}
