代码检查字符串是否在目录文件中,我认为我有问题
我的searchFile()
函数
argv1
是文件夹argv2
是要搜索的字符串 argv3
是结果文件
#include "dirent.h"
#include<stdio.h>
#include<stdlib.h>
int searchFile(FILE* File1, char * buffer);
void saveFile(int flag, char * File1Name, char* logAddress);
int main(int argc, char **argv) {
int flag = 0;
DIR* dir;
FILE* File1;
char * buffer=0;
long length;
char address[1000];
struct dirent *pDirent;
dir = opendir(argv[1]);
if (dir == NULL)
{
printf("Cannot open directory '%s'\n", argv[1]);
flag=1;
}
//convert the signeture file to string
FILE * f = fopen(argv[2], "rb");
if (f)
{
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = (char*)malloc(length*sizeof(char));
if (buffer)
{
fread(buffer, 1, length, f);
}
fclose(f);
}
if (buffer)
{
strcpy(address, argv[1]);
while ((pDirent = readdir(dir)) != NULL)
{
if (pDirent->d_name[0] != '.')
{
printf("[%s]\n", pDirent->d_name);
strcat(address, pDirent->d_name);
File1 = fopen(address, "rb");
printf("%s.\n", address);
if (!File1) printf("PROBLEM.\n");
flag = searchFile(File1, buffer);
saveFile(flag, pDirent->d_name,argv[3]);
strcpy(address, argv[1]);
}
}
closedir(dir);
}
free(buffer);
system("PAUSE");
return (0);
}
输入:目录中的文件,FILE *
函数搜索字符串是否在文件中并将结果发送到保存文件函数
输出:无
int searchFile(FILE* File1, char * buffer)
{
int char1, flag = 0,i=0;
char temp[1000];
while ((char1 = fgetc(File1)) != EOF && flag == 0)
{
if (*(buffer + i) == char1)
{
i++;
if (strlen(buffer) == i)//if the whole string is in the FILE.
{
flag = 1;
}
}
else
{
i = 0;
}
}
fclose(File1);
return flag;
}
输入:dir中的文件,FILE * int flag
该功能打印所有文件并告知谁受感染以及谁不是
void saveFile(int flag, char * File1Name, char *logAddress)
{
FILE* File2 = fopen(logAddress, "a+");
if (File2)
{
fprintf(File2, File1Name);
if (flag == 1)
{
fprintf(File2, " INFECTED!\n");
}
else
{
fprintf(File2, " not infected\n");
}
}
fclose(File2);
}