I'm writing a program that counts all of the tokens in a given file ("search"). I can count the number of "#" signs in the file, but I need to name a number of other tokens... {}()/... and output how many where found in the file.
Can anyone offer suggestions as to the best method to accomplish this? Right now I am thinking of having each value set up as it's own variable - such as delim1 = #, delim2 = {, and then creating a function from my current code to call each time. Is there a more efficent/faster method? Here is my current code:
Code:
#include <stdio.h>
#include <string.h>
#define MAX_LINE 80
int main()
{
char line[MAX_LINE]; /* Max length of line is 80 */
char delim[] = "#"; /* Testing just # delim */
char *words,
*ptr;
FILE *fptr;
int count = 0;
int ch;
int linect;
fptr = fopen ("search", "r"); /* Test file "search" */
/* File does not exist or there are not proper permissions set */
if (fptr==NULL)
printf ("\nCannot open the file\n\n");
else
{
/* While the file is not at EOF, End of File, loop */
while ((ch=fgetc(fptr)) !=EOF)
{
/* Reads a line from the file and sets the ptr variable to the line */
fgets(line,MAX_LINE,fptr);
ptr=line;
linect = linect++;
printf("Line reads: %s\n", ptr);
/* Loop while looking for delims, when no delims are found it is NULL */
while ((words = strtok(ptr, delim)) != NULL)
{
printf("Strtok result: %s\n", words);
count++;
ptr = NULL;
}
}
printf("\nNumber of delims in the file: %d \n\n",(count-linect));
fclose(fptr);
}
return 0;
}
This is working with just one delim on the two lines included in the "search" file below:
This # is a # test # file.
End#