I need to open a file, then count the number of time a certain sequence appears in the file, with space being ignore. The file name and the sequence are entered by the using through the command line. Here's my approach: I open the file, then store the content to an array, then remove all the space from that array and store it to another array. Then, I search for sequence and count the number of times it appear. This is my code:
#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';
}
I tested it, and I'm having problem with getting the content from the file. Sometimes it works, but most of the time, all I got is an empty string.