-1

我需要打开一个文件,然后计算某个序列在文件中出现的次数,空格被忽略。文件名和顺序通过命令行输入。这是我的方法:我打开文件,然后将内容存储到一个数组中,然后从该数组中删除所有空间并将其存储到另一个数组中。然后,我搜索序列并计算它出现的次数。这是我的代码:

#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';

}

我对其进行了测试,但在从文件中获取内容时遇到了问题。有时它可以工作,但大多数时候,我得到的只是一个空字符串。

4

1 回答 1

1

你的代码有一些问题,编译器应该给你警告(不要忽略编译器):

应该声明第一个函数,而不仅仅是定义所以添加:

void removeBlanks( char *dest, const char *src);

在主要之前。根据 C99 标准(5.1.2.2.1 程序启动main应该声明一个返回值int main(int argc, char *argv[]),你应该添加适当的return语句。

就像上面指出的那样,不需要强制转换 malloc

上面的问题并不是为什么它不起作用……而是因为你在错误的变量上使用了strchr函数并且以错误的方式:

pointer = strchr(pointer,argv[2]);

应该

pointer = strchr(temp, *argv[2]);

因为temp是指向您从文件中读取的内容的指针,并且strchr需要 achar作为第二个参数,而不是 a char *。如果你想搜索一个字符串,你必须使用strstr,这需要char *类似:

pointer = strstr(temp, argv[2]);

此外,由于您从第二个字符串中删除空白tempRaw并将新字符串存储在temp第二个字符串中会更短并且最后会得到垃圾,因此您应该初始化内存,如:

tempRaw = calloc(1, size);

可能还有其他错误,但是这些更改使它对我有用...

于 2013-11-10T08:17:08.437 回答