Thread: Counting words in a file

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    124

    Counting words in a file

    I am using the following program to print the document GPA.txt and to figure out how many times the word "pets" is in that document.
    I manually counted it and it's in there 4 times.
    The document prints, but it keeps telling me that 'pets' is not in the file (0 times).
    Please let me know what I am doing wrong.
    Thank you

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stddef.h>
    
    int main (){
    	char c;
    	char inputText[500];
    	int countSame=0;
    
    	//printf("Please enter the name of your file:");
    	//scanf("%s",fileName);
    
    	FILE* inputFile;
    
    
    	inputFile=fopen("C:\\Documents and Settings\\User\\My Documents\\GPA.txt","r");
    
    	if (inputFile==NULL){
    		printf("Failed to open");
    		exit(-1);
    	}
    
    	fgets(inputText, 500, inputFile);
    
    	while ((c=getc(inputFile))!=EOF){
    		printf("%c",c);
    
    		if( strcmp( inputFile, "pets" ) == 0 ) {
    			countSame++;
    		}
    	}
    
    	printf("There are %i matches for pets", countSame);
    	system("Pause");
    
    
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    If you had included string.h, you would have discovered that the first argument of strcmp has to be a char*, as opposed to a FILE *.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    124
    so how would i go about fixing that
    i tried using c and c* and thats not working

  4. #4
    Registered User
    Join Date
    Jan 2008
    Posts
    124
    i also tried inputText with no luck

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Use inputText, and put fgets(inputText, 500, inputFile) into the loop instead of you getc() call.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting a file with a lot of words.
    By samus250 in forum C Programming
    Replies: 28
    Last Post: 04-27-2008, 01:36 PM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  3. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM
  4. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM