Thread: find first occurance of a string in a file

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    8

    Question find first occurance of a string in a file

    hi all post #1 :]

    i've got a file that is generated by a program i've made. the first few lines of the file are comments, deliminated by #'s. i'd like to be able to do a fscanf on each line of the file, disregarding the first few lines, to input data. now the number of commented lines at the top of the file may be a few or a bunch. here is an example of the file i'm talking about...

    # a bunch of commments here...
    # cprogramming.c is cool!
    # etc...

    prog etc and so on

    i need to find the first occurance of the word "prog" because that is the line at which my "important" data starts. is there a simple way to do this? i was thinking read each word into a string and strcmp it for "prog" but i'm sure it can be done more efficiently. thanks!

    -justin

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    if you're using string classes, use the find() function.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Read a line and test the first non-whitespace character for '#'. Do this until you run out of #'s and then use strstr on the line to find "prog". If the string is on a line by itself you could use strcmp, but if there are other items on the same line you will have to check and see if your string is there, then find out where so that you can continue processing the important stuff.

    >if you're using string classes, use the find() function.
    This is the C board.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM