Hi, I need more help.
I need to read from a file(input.txt) and get the number of occurrences of each word and produce the result in the seperate text file as well as screen,
everything works but it doesn't produce the text file (ie: output.txt).
can someone help please:
THanks
Code:
#include "stdafx.h"
#include <stdio.h>
#define LEN_TOTAL 21
int _tmain(int argc, _TCHAR* argv[])
{
int word_length_occurrence[ LEN_TOTAL ] = { 0 };
char string[700]={0},
tempStr[300]={0},
*tokenPtr;
size_t i, numLines,
maxLength = 0;
FILE * pFile;
pFile = fopen ("input.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
while (!feof(pFile)) {
fgets( tempStr, sizeof( tempStr ), pFile );
strcat( string, tempStr );
}
tokenPtr = strtok( string, " \n" );
while ( tokenPtr != NULL ) {
maxLength = strlen( tokenPtr );
word_length_occurrence[ maxLength ]++;
tokenPtr = strtok( NULL, " .,\n" );
}
printf( "%8s%15s\n", "Word Length", "Occurrences" );
for ( i = 1; i < LEN_TOTAL; i++ )
printf( "%4d%15d%c", i, word_length_occurrence[ i ], '\n' );
printf( "\n" );
getchar();
fclose (pFile);
}
FILE * pFile2;
pFile2 = fopen ("output.txt","w+");
if (pFile!=NULL) {
fprintf( pFile2,"%8s%15s\n", "Word Length", "Occurrences" );
for ( i = 1; i < LEN_TOTAL; i++ )
fprintf( pFile2,"%4d%15d%c", i, word_length_occurrence[ i ], '\n' );
fclose(pFile2);
}
return 0;
}