我需要打开一个文件,然后计算某个序列在文件中出现的次数,空格被忽略。文件名和顺序通过命令行输入。这是我的方法:我打开文件,然后将内容存储到一个数组中,然后从该数组中删除所有空间并将其存储到另一个数组中。然后,我搜索序列并计算它出现的次数。这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main (int argc, char *argv[])
{
char *tempRaw;
char *temp;
int size;
//Input check
if(argc != 3)
{
fprintf(stderr, "Usage: %s Input Search\n", argv[0]);
exit(1);
}
//Open files
FILE *input = fopen(argv[1],"r");
//Check for file
if(input == NULL)
{
fprintf(stderr, "Unable to open file: %s\n", argv[1]);
exit(1);
}
//Get the file size
fseek (input,0,SEEK_END);
size = ftell(input);
rewind(input);
//Allocate memory for the strings
tempRaw = (char*) malloc(sizeof(char)*size);
temp = (char*) malloc(sizeof(char)*size);
//Copy the file's content to the string
int result =0;
int i;
fread(tempRaw,sizeof(char),size,input);
//Remove the blanks
removeBlanks(temp,tempRaw);
fclose(input);
char *pointer;
//Search for the sequence
pointer = strchr(pointer,argv[2]);
// If the sequence is not found
if (pointer == NULL)
{
printf("%s appears 0 time",argv[2]);
return;
}
else if (pointer != NULL)
{
//Increment result if found
result ++;
}
while (pointer != NULL)
{
//Search the next character
pointer = strchr(pointer+1,argv[2]);
//Increment result if the sequence is found
if (pointer != NULL)
{
result ++;
}
//If the result is not found, pointer turn to NULL the the loop is break
}
printf(" Sequence : %s\n",temp);
printf("%s appears %d time(s)\n",argv[2],result);
}
void removeBlanks( char *dest, const char *src)
{
//Copy source to destination
strcpy(dest,src);
char *old = dest;
char *new = old;
//Remove all the space from destination
while (*old != '\0')
{
// If it's not a space, transfer and increment new.
if (*old != ' ')
{
*new++ = *old;
}
// Increment old no matter what.
old++;
}
// Terminate the new string.
*new = '\0';
}
我对其进行了测试,但在从文件中获取内容时遇到了问题。有时它可以工作,但大多数时候,我得到的只是一个空字符串。