我需要打开一个文件,然后计算某个序列在文件中出现的次数,并忽略空格。文件名和序列通过使用命令行输入。这是我的方法:我打开文件,然后将内容存储到数组,然后从该数组中删除所有空间并将其存储到另一个数组。然后,我搜索序列并计算它出现的次数。这是我的代码:文件输入/输出和搜索
#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';
}
我测试了它,并且遇到了从文件中获取内容的问题。有时它是有效的,但大部分时间,我所得到的只是一个空字符串。
这压痕不利于readabil ity ...也,[不要强制'malloc()']的返回值(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858# 605858),'sizeof(char)'总是1,所以它是多余的。 – 2013-11-10 07:53:38