Hi there. Im trying to extract words from a file and print them out one by one. Eg if the file contained "The flying machine" it will print to stdout on separate lines,
"The"
"flying"
"machine"
So i assumed i would use the library function strtok to achieve this as it says it splits a string up into tokens using delimiters. I have written some code so that the file is opened for reading and if the user wants, it can convert the strings to lower case also. So with the splitString function i am wanting to read in the file and take the words in it and print them all out separately in either retained or lower case. I no there is something seriously wrong with it at the moment. Still not really sure how to write it as i guess i should be reading each word into a char* buffer that is only able to hold buffSize-1 chars in it and print it out in retained or lower case the continue to the next word or do you do it all in one big array holding all the words from the file and somehow make sure that they are no longer than buffSize-1 chars (10-1) and print them out on seperate lines. Any help would be appreciated.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define BUFFER_SIZE 10
#define MAX_WORD_LENGTH 256
#define USE "Usage: strings [-p] [file]\n"
char strings[MAX_WORD_LENGTH] = {'\0'};
int splitString(FILE *file, char *buffer, int bufferSize, int retainCase);
int convertStringToLower(FILE *file);
int main(int argc, char *argv[])
{
char *result = NULL;
FILE *file = NULL;
int preserveCase = 0;
int error = 0;
if((argc > 3) || ((strcmp(argv[1], "-c") != 0) && (argc > 2)) || (argc < 2))
{
error++;
}
if(strcmp(argv[1], "-p") == 0)
{
preserveCase = 1;
file = fopen(argv[2], "r");
}
if(strcmp(argv[1], "-p") != 0)
{
file = fopen(argv[1], "r");
}
if(error)
{
fprintf(stderr, USE, argv[0]);
return EXIT_FAILURE;
}
if(!preserveCase)
{
splitString(file, result, BUFFER_SIZE, 0);
}
if(preserveCase)
{
while(fgets(strings, MAX_WORD_LENGTH, file) != 0)
{
splitString(file, result, BUFFER_SIZE, 1);
}
}
fclose(file);
return EXIT_SUCCESS;
}
int splitString(FILE *file, char *buffer, int buffSize, int retainCase)
{
char delims[] = " ,().";
if(retainCase)
{
while(fgets(buffer, buffSize - 1, fp))
{
buffer = strtok(string, delims);
while(buffer != NULL)
{
printf("%s\n", buffer);
buffer = strtok(NULL, delims);
}
}
}
if(!retainCase)
{
convertStringToLower(file);
while(fgets(buffer, buffSize - 1, fp))
{
buffer = strtok(strings, delims);
while(buffer != NULL)
{
printf("%s\n", buffer);
buffer = strtok(NULL, delims);
}
}
}
return EXIT_SUCCESS;
}
int convertStringToLower(FILE *file)
{
int i = 0;
while(fgets(strings, MAX_WORD_LENGTH - 1, file) != 0)
{
for(i = 0; i < MAX_WORD_LENGTH - 1; i++)
{
strings[i] = tolower(strings[i]);
}
}
return EXIT_SUCCESS;
}