Thread: word search in a text file

  1. #1
    Registered User
    Join Date
    Nov 2008

    Thumbs up word search in a text file

    hey, I am writing a c program that searches a text file for a keyword and count the number of times it occurs in the text file.

    this is what I have so far

    printf("Enter A Single keyword:");
    Last edited by Salem; 11-20-2008 at 12:12 AM. Reason: [code][/code] tags AROUND THE CODE PLEASE, don't just slap them in to keep the rules happy

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Even though fscanf isn't the safest function, this should work IF you care about keywords that are seperated with whitespaces. It won't find cat in the string "cats" for example, the latest being a bit more complicated but still easily achieved.

    You can also check fscanf for errors. It returns EOF when input error.

    Also, note that fscanf can easily cause a buffer oveflow in your program. Even if you give a big buffer for key_temp, the file might not contain whitespaces and might be long. This is a serious error for a generic word searcher. Lets say you want to scan a 2mb file. You will have to have a key_temp buffer 2mb just to be sure. Which means that you have to dynamically allocate space for your key_temp buffer.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    1. See the FAQ for why feof() is wrong to control a loop.

    2. Read the manual page for strcmp() to find out what it returns when strings are equal.

    3. Having established equality, this is pointless (and wrong)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008

    As Salem mentioned (keyword==key_temp), is not doing what you think it is doing unless you are comparing that the left and right side are in fact pointing to the same address space!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

Tags for this Thread