#define _WIN32_WINNT 0x0400 #include #include #include #include //structure definitions //this structure holds a single word typedef struct { char * pszString; } WordStruct; //prototypes bool IsPunctuation(char vcCarlos); bool IsWhiteSpace(char vcGuy); char * ReadInFile(char * vpszFileName, long * vplLength = NULL); int main(int argc, char *argv[]) { //declare variables WIN32_FIND_DATA FindFileData; HANDLE hFind; long lSize; //size of file char * pszBuffer; //buffer to hold contents of file WordStruct * pwsWords; //list of words in the file int nWords = 0; // number of words in the list int nStart = 0; // start of next word int nCount = 0; // number of times we found the word char szWord[1025]; //the word to find printf ("Target file is %s.\n", argv[1]); hFind = FindFirstFile("c:\\*.txt", &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError ()); } else { printf ("The first file found is %s\n", FindFileData.cFileName); FindClose(hFind); } cout<<"This file will be opened. What word would you like to search for?\n"; cin.getline(szWord, 1024); //strcpy (str,"c:\\"); //strcat(str,FindFileData.cFileName); //load the file into memory pszBuffer = ReadInFile("C:\\both.txt",&lSize); //check for an error if(pszBuffer == NULL) { printf("Error reading file.\n"); return 0; } //we want comparisons to be case-insensitive, so make whole // file lowercase strlwr(pszBuffer); //declare array of words pwsWords = (WordStruct *)malloc(lSize*sizeof(WordStruct)); //make sure the memory was allocated if(pwsWords == NULL) { printf("Error allocating pwsWords.\n"); //free memory free(pszBuffer); return 0; } //parse the file // Note that i <= lSize because '\0' is at pszBuffer[lSize] for(int i = 0; i <= lSize; i++) { //if this character is punctuation, it is replaced by white space if (IsPunctuation(pszBuffer[i]) ) { pszBuffer[i] = ' '; } //if this is whitespace, copy the word if(IsWhiteSpace(pszBuffer[i])) { //see if we have simply encountered two whitespace in a row if(nStart == i) { nStart++; continue; } //allocate memory pwsWords[nWords].pszString = (char *)malloc(sizeof(char)*(i-nStart+1)); //make sure memory was allocated if(pwsWords[nWords].pszString == NULL) break; //assume done and just exit the loop //copy the string strncpy(pwsWords[nWords].pszString, pszBuffer+nStart,i-nStart); //close the string pwsWords[nWords].pszString[i-nStart] = '\0'; //next word nWords++; nStart = i+1; //a little display cout << "Word " << nWords << " is " << pwsWords[nWords-1].pszString << endl; } } //count number of time we found our word for(i = 0; i < nWords; i++) { if(strcmp(szWord,pwsWords[i].pszString) == 0) nCount++; } cout << "Found " << szWord << " " << nCount << " times.\n"; cout<