foreword
We may encounter such a problem in our work. The content of a file is messy (mostly seen in the output log), and we need to find all the statements containing a certain field. If we do not use other methods, it is really a headache. things. Next, I will provide a code that can solve similar problems.
programming
1. Let’s take the file curent.log with the suffix .log as an example (the code is variable, and it can also be a file with other suffix formats), as shown in the figure below. The content inside is very messy, including a lot of TableKey . If we want to find the statement that contains TableKey: 986375 , it is simply difficult to do it manually. 2. Don't be afraid, let's directly upload the code, sort out all the statements containing TabelKey: 986375 , and write them into a new file new.log . Tips: The curent.log file should be placed in the debug directory. Different editors have different debug directories. You can search for where the directory is in the project.
// 引入头文件
#include "stdafx.h"
#include <iostream>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
#define FILESIZE 1024
string PATHREAD = "curent"; // 需要读取的文件名(杂乱无章的那个)
string PATHWRITE = "new"; // 写入到新的文件名(不用提前创建,代码会自动创建该文件)
string TABLEKEY = "986375"; // 读取有“986375”字段标识的语句
// 编辑读取文件的函数
FILE *READFILE()
{
PATHREAD += ".log"; // 文件后缀名(可根据实际文件后缀进行修改)
FILE* fd = fopen(PATHREAD.c_str(),"r"); //文件追加 读取用r
if (fd == NULL)
{
return NULL;
}
return fd;
}
// 编辑写入新文件的函数
FILE* WRITEFILE()
{
PATHWRITE += ".log"; // 新文件后缀名保持一致
FILE* fd = fopen(PATHWRITE.c_str(),"w"); // 文件追加,写入用w
if (fd == NULL)
{
return NULL;
}
return fd;
}
// 在main函数内调用
int main()
{
char temp[FILESIZE];
string Table = "TableKey:"; // 标识字段
Table += TABLEKEY; // 完善要查找的字段
FILE *write = WRITEFILE();
FILE *read = READFILE();
if (write==NULL || read==NULL)
{
exit(0);
}
// 读取、写入成功之后,进行数据操作
char *s = fgets(temp,FILESIZE,read);
while (s!=NULL)
{
if (!strstr(temp,Table.c_str()))
{
memset(temp,0,FILESIZE);
s = fgets(temp,FILESIZE,read);
continue;
}
fputs(temp,write);
memset(temp,0,FILESIZE);
s = fgets(temp,FILESIZE,read);
}
fclose(write);
fclose(read);
return 0;
}
3. Execute the above code in the editor (sometimes encountering version compatibility issues), a new file new.log will be created, and its content is what we need, as shown in the figure below. All statements containing TableKey:986375 are listed so we can continue our work.