Sample Input files input.txt: golf foxtrot echo delta charlie beta alpha SAMPLE
ID: 3634865 • Letter: S
Question
Sample Input filesinput.txt:
golf
foxtrot
echo
delta
charlie
beta
alpha
SAMPLE OUTPUT
Enter an input file name: input.txt
The input file contains 7 distinct words
alpha, 7
beta, 6
charlie, 5
delta, 4
echo, 3
foxtrot, 2
golf, 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define fileNameLength 256
typedef struct {
char word[256];
int lineNumber;
} word;
int main()
{
FILE *inputFile;
char inputFileName[256] = {0};
int fileLine = 0;
int wordsCountedSoFar = 0;
int i;
char bufferWord[256];
char bufferChar;
char *result = NULL;
char delims[] = " ";
int foundWord = 0;
word Dictionary[1000];
printf("Program: Structs ");
do
{
printf("Enter an input file name: ");
fgets(inputFileName, fileNameLength, stdin);
inputFileName[strlen(inputFileName) - 1] = '';
if ((inputFile = fopen(inputFileName, "r")) == NULL)
{
printf("Unable to open "%s": %s ", inputFileName,
strerror(errno));
}
} while (inputFile == NULL);
for(i = 0; i < 1000; ++i)
{
Dictionary[i].lineNumber = 0;
}
while (fgets(bufferWord, 256, inputFile) )
{
++fileLine;
printf(" words found in line %d, %s ",fileLine, bufferWord);
bufferWord[strlen(bufferWord) -1] = '';
result = strtok( bufferWord, delims );
while( result != NULL ) {
printf( ""%s" ", result );
for(i = 0; i < wordsCountedSoFar; ++i)
{
if(strcmp(Dictionary[i].word, result) == 0)
{
break;
}
}
strcpy(Dictionary[i].word, result);
if(wordsCountedSoFar <= i + 1)
wordsCountedSoFar = i + 1;
if( Dictionary[i].lineNumber == 0)
Dictionary[i].lineNumber = fileLine;
/** store the distinct words **/
result = strtok( NULL, delims );
}
}
fclose(inputFile);
for(i = 0; i < 1000; ++i)
{
if(Dictionary[i].lineNumber > 0)
printf("word %s found at line:%d ", Dictionary[i].word, Dictionary[i].lineNumber);
}
return 0;
}