Thread: Mysteriously losing contents of a string between file I/O operations

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    2

    Mysteriously losing contents of a string between file I/O operations

    Haven't worked with file I/O very much, and it feels like there's something happening behind the scenes here that I don't understand.

    Here's the code I'm writing:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    char* getTeamCode(char* team);
    int checkTeamInGame(char* teamCode, char* game);
    char* getCell(char* line, int index);
    int findNextCell(char* line, int index);
    void addLineCSV(char* line, char* csv);
    
    
    
    int main()
    {
        char* OSUteamCode = malloc(sizeof(char)*5);
        char* OSU = "Oregon State";
        char* OSUgameLog = "OSUgamelog.csv";
        char* fileLine[1024];
        FILE* fp;
    
        OSUteamCode = getTeamCode(OSU);
    
        fp = fopen("2012/game.csv","r");
    
    
    
        while(fgets(fileLine,1024,fp))
       {
           if(checkTeamInGame(OSUteamCode,fileLine)){
                printf("Writing game %s\n",fileLine);
                addLineCSV(fileLine,OSUgameLog);
            }
        }
    
        fclose(fp);
    
        return 0;
    }
    
    
    
    
    /* Takes a team name in the form of a string
    Returns the team's ID number as a string */
    char* getTeamCode(char* team)
    {
        FILE* stream = fopen("2012/team.csv","r");
    
        char line[1024];
        char teamCode[10];
    
        while (fgets(line, 1024, stream))
        {
            char temp[100];
            int i = 0;
            int j = 0;
    
            i = findNextCell(line, i);        // Look for first comma
    
            i++;                          // Hop past the comma and quote
    
            while(line[i] != '"')           // Copy current team name into temp
            {
                temp[j] = line[i];
                i++;
                j++;
            }
            temp[j] = '\0';                 // Append temp with null
    
            if(!strcmp(team, temp))         // Check to see if we have the right team
            {
                i = 0;
                j = 0;
                while(line[i] != ',')
                {
                    teamCode[j] = line[i];
                    i++;
                    j++;
                }
                teamCode[j] = '\0';
                break;
            }
    
            free(temp);
        }
    
        fclose(stream);
        return teamCode;
    }
    
    
    
    /*Checks to see if a specific team is part of a game
    Takes a team's code and a specific game
    Returns 1 if a team is in the game, 0 if not*/
    int checkTeamInGame(char* teamCode, char* game)
    {
        char* temp;
        int i = 0;
    
        i = findNextCell(game, i);  //Skip game ID cell
    
        i = findNextCell(game, i);  //Skip date Cell
    
        temp = getCell(game, i);    //Store first team ID
        if(!strcmp(temp,teamCode))  //Check it
            return 1;
        else
        {
            i = findNextCell(game, i);      //Go to cell with Second team ID
            temp = getCell(game,i);         // Store second team ID
            if(!strcmp(temp,teamCode))      // Check it
                return 1;
            else
                return 0;
        }
        puts(teamCode);
    
    }
    
    
    /*Gets the content of a cell and returns it
    Takes a line of a CSV and an index for that line
    Returns a string containing the contents of one cell*/
    char* getCell(char* line, int index)
    {
        char* temp = malloc(sizeof(char)*100);
        int i = index;
        int j = 0;
    
        while(line[i] != ',' && line[i] != '\n')
        {
            temp[j] = line[i];
            i++;
            j++;
        }
        temp[j] = '\0';
    
        return temp;
    }
    
    
    /*Moves an index to the next cell in a line of a CSV
        THIS WILL NOT WORK PROPERLY IF THE CELL CONTAINS A RELEVANT COMMA
    Takes a line of a csv and an index
    Returns an index*/
    int findNextCell(char* line, int index)
    {
        int i = index;
    
        if(line[i] == ',') // Check to see if we're starting on a comma by mistake
            i++;
        while(line[i] != ',') // Travel down string to the next comma
            i++;
        i++; // Hop past comma
    
        return i;
    }
    
    
    /*Appends a CSV with the given line of text */
    void addLineCSV(char* line, char* csv)
    {
        FILE* fp = fopen(csv, "a+");
        fprintf(fp,"%s",line);
        fclose(fp);
    }

    What I can't figure out is why the placement of the code on line 21 above matters.

    It grabs the correct string just fine. If I write a printf just below it, it prints the string it should correctly. However, if I do a printf of the string OSUteamCode below the fopen call on line 23, it prints blank.

    So the first thing I did was move it below the fopen line. It worked, finding and outputting the first game in "game.csv" just fine, but not the other 11. Debugging with printf shows that the contents of OSUteamCode again disappear after the fopen call in the addLineCSV function.

    I'm not understanding why that happens. The only thing I can figure is there's something going on with the file I/O commands that I just don't understand, but I can't find anything online that explains what that might be.
    Last edited by kriskrosed; 10-24-2013 at 03:32 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    getTeamCode() is returning a pointer to the (first element of) an array that is local to that function. That array is not guaranteed to exist after the function returns. Any usage of that return value (in main()) therefore gives undefined behaviour.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Oct 2013
    Posts
    2
    Ah, got it. Thank you much for the quick reply.

  4. #4
    C lover
    Join Date
    Oct 2007
    Location
    Virginia
    Posts
    266
    If you malloc the memory after declaring your pointer it would work since that would be stored on the heap.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-08-2009, 08:54 PM
  2. Using string operations to save part of a file path
    By JackR in forum C++ Programming
    Replies: 4
    Last Post: 05-31-2007, 03:48 PM
  3. storing text file contents into a string
    By m.mixon in forum C Programming
    Replies: 4
    Last Post: 07-20-2006, 11:52 AM
  4. vector contents mysteriously vanishing
    By Loduwijk in forum C++ Programming
    Replies: 5
    Last Post: 03-24-2006, 11:09 AM
  5. String is getting mysteriously knackered
    By kzar in forum C Programming
    Replies: 2
    Last Post: 04-10-2005, 08:02 AM