Code:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#define MAX_WORD_LENGTH 31
#define MAX_WORDS 42000
/* Function prototypes */
int readFile(char* inputFileName, int* wordCount, char array[][MAX_WORD_LENGTH], int flag);
//int qsort(char array[][MAX_WORD_LENGTH], int* wordCount);
int writeToFile(char* outFileName, int wordCount, char array[][MAX_WORD_LENGTH]);
void printTime(time_t begin);
void usage(char* processName);
// enter any other function prototype you may wish
int main(int argc, char* argv[])
{
time_t begin;
char array[MAX_WORDS][MAX_WORD_LENGTH];
int wordCount = 0;
time(&begin);
switch (argc)
{
case 3:
readFile(argv[1], &wordCount, array,0);
writeToFile(argv[2], wordCount, array);
break;
case 4:
{
if (strcmp(argv[1], "-s") == 0)
{
readFile(argv[2], &wordCount, array,1);
writeToFile(argv[3], wordCount, array);
}
else if (strcmp(argv[1], "-t") == 0)
{
readFile(argv[2], &wordCount, array, 1);
writeToFile(argv[3], wordCount, array);
printTime(begin);
}
else
{
usage(argv[0]);
}
break;
}
case 5:
default:
usage(argv[0]);
break;
}
return 0;
}
// Define all your functions here
void printTime(time_t begin)
{
printf("\nThe time at which it began was %ld", begin);
}
void usage(char* processName)
{
printf("Usage %s [-s] [-t] inputFileName outputFileName\n", processName);
}
int readFile(char* inputFileName, int* wordCount, char array[][MAX_WORD_LENGTH], int flag)
{
FILE *fp;
fp = fopen(inputFileName, "r");
if(fp == NULL)
{
printf("\n Unable to open the file. Aborting");
exit(EXIT_FAILURE);
}
if(flag == 0)
while(fscanf(fp, "%s", array[(*wordCount)++]) > 0);
else if(flag == 1)
{
int i = 0, j= 0, k= 0;
//sort the elements of the array
while(fscanf(fp, "\n%s", array[(*wordCount)++]) > 0)
{
if(*wordCount> 1)
{
for(i =0 ;i<*wordCount; i++)
{
j = strcmp(array[i],array[*wordCount]);
if(j > 0)
{
k = *wordCount;
strcpy(array[k+1], array[k]);
for(k = *wordCount; k > i; k--)
strcpy(array[k], array[k-1]);
break;
}
}
}
}
};
fclose(fp);
return 0;
}
int writeToFile(char* outFileName, int wordCount, char array[][MAX_WORD_LENGTH])
{
int i = 0;
FILE *fp;
fp = fopen(outFileName, "w");
if(fp == NULL)
{
printf("\n Unable to open the file. Aborting");
exit(EXIT_FAILURE);
}
for(i = 0; i< wordCount-1; i++)
{
fprintf(fp, "%s\n", array[i]);
}
fclose(fp);
return 0;
}
I have a file dictionary.txt which has some 41000 plus words in it and i want to read it. So how do i overcome this problem of stack overflow...?