Colm Moore
Colm Moore

Reputation: 21

How to repeatedly append text to a string in C?

I am trying to repeatedly append a line from a file to a string called lines. My code works fine when I just try and print the lines but as I have to parse the information, I need to store it.

int main(int argc, char *argv[])
{
    // Check for arguments and file pointer omitted
    FILE *f = fopen(argv[1], "r");
    char *times;
    int i = 0;

    for (i = 0; i < 2000; i++)
    {
        char line[80];
        if (fgets(line, 80, f) == NULL)
            break;

        //I want every line with the text "</time> to be added to string times
        if(strstr(line, "</time>"))
        {
            times = strcat(times, line);  //This line is my problem
        }
    }

    printf(times);

    fclose(f);
    return 0;
}

Upvotes: 1

Views: 354

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Your code doesn't work because you need to allocate space for the string. You declared items as a char pointer, but you don't make it point to valid memory, then strcat() tries to write to it causing udefined behavior.

Try this

char items[1024];

 items[0] = '\0';

the items[0] = '\0'; is because strcat() will search for the '\0' byte in the first string and append the second string from it to the end of the second string.

You should note that if the strings you are going to concatenate together are too long to fit items then problems will happen again.

In that case you either need to use malloc()/realloc() to allocate space dynamically or calculate the total length of the resulting string and then allocate enough space for it.

Upvotes: 3

Related Questions