Thread: New to C trouble with strtok and storing the values

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    14

    New to C trouble with strtok and storing the values

    I need to read variable name and value combinations from a config file and store the results. I seem to be having no trouble storing the int value, but the strings I am having trouble with. In the first part I am doing some command line processing which looks to be working fine, reading from the config file is tripping me up. Attached are 2 files. project.c is the source and settings.txt is the config

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    what kind of error do you get?

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    14
    well...this is what the output gives me

    token = group1
    groupName = group1
    token = 7
    timeToRun = 7token = log.txt
    logFilename = log.txt
    Groupname = TimeToRun = 7 ConfigFilename = settings.conf LogFilename = �����y����l-y������Y.y�p1� ��������

    so basically, when I try to store those values that are held in the char* token, they wont save to the global variable Groupname, and LogFilename. I have no idea why. I'm assuming that maybe I need to do a malloc somewhere maybe??? i really don't know C at all and I am just guessing.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Your logfilename is a pointer to a local variable.

    When readConfigFile() returns, the string variable you have been using goes out of scope.

    You need to allocate space for, and strcpy() the result.
    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.

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    14
    is that the same problem with the group name too? is that why, at the end when I print out all the variables, the group name is apparently empty?

    and how would I do the allocation? malloc(sizeof(char*))???

  6. #6
    Registered User
    Join Date
    Mar 2010
    Posts
    14
    I figured it out. Thanks so much for the help guys. You have NO idea how long I sat and stared at this. Although I feel like I should have realized what was happening, I'm just not all that familiar with pointers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strtok problem
    By vin_pll in forum C++ Programming
    Replies: 13
    Last Post: 10-05-2008, 02:57 PM
  2. simple question about strtok
    By Axel in forum C Programming
    Replies: 8
    Last Post: 10-16-2005, 06:06 AM
  3. help with strtok
    By requiem in forum C Programming
    Replies: 5
    Last Post: 04-29-2003, 04:10 PM