Maxim Neaga
Maxim Neaga

Reputation: 961

C strtok and strcpy

I have a text file, similar to the following:

Name1: ID1
Name2: ID2
Name3: ID3

I am trying to parse it to get

Name1
Name2
Name3

stored in a variable.

I wrote the following function:

/*
 *  filename    Name of file to read
 *  result      The result will be stored here
 */

void readlist(char* filename, char* result) {
    FILE *fp;
    char buffer[2048];
    memset((void *)result, '\0', BUFFER_SIZE);

    fp = fopen(filename, "r");

    while (fgets(buffer, sizeof(buffer), fp)) {
        char *token = NULL;
        token = strtok( buffer, ":" );
        strcat(result, token);
    }

    fclose(fp);
}

However when I call it:

char result[2048];
readlist("test.txt", result);
printf("%s", result);

I'm getting an empty output. It seems that strtok() messes up the data, but I might be wrong.

What am I doing wrong here?

Thank you in advance!

Upvotes: 1

Views: 2642

Answers (4)

Floris
Floris

Reputation: 46375

I ran your code (or at least, I created a single program from the snippets of your code) and it worked fine for me:

#include <stdio.h>
#include <string.h>

void readlist(char* filename, char* result);

int main(void) {
char result[2048];
readlist("test.txt", result);
printf("%s", result);
}

void readlist(char* filename, char* result) {
    FILE *fp;
    char buffer[2048];

    fp = fopen(filename, "r");

    while (fgets(buffer, sizeof(buffer), fp)) {
        char *token = NULL;
        token = strtok( buffer, ":" );
        strcat(result, token);
    }


    fclose(fp);
}

When I ran it on your input file, I got as output

Name1Name2Name3

Exactly as expected.

This was using the gcc compiler version 4.2.1 on Mac OS . It suggests your code isn't as far off as you think (whether the compiler initializes the string to 0 before starting is implementation dependent, apparently). To be safe though, you need to make sure your initial result is all zeros. You could do

char result[2048] = {'\0'};

This would guarantee all elements are initialized to zero. Another method would be to use

static char result[2048];

Since any variable declared static will be initialized to zero.

Finally, things like

result[0] = '\0';

would start the string with zero length - and whatever follows doesn't matter. This is probably the cleanest.

Upvotes: 1

dmg
dmg

Reputation: 4481

You never initialized result, before the call to readlist or after.

just add before the call to readlist: strcpy(result, "");

Upvotes: 2

anshul garg
anshul garg

Reputation: 503

char result[2048];

Initialize this statement otherwise result will contain garbage values as its an auto variable.

So use char result[2048] = ""; before readlist() is called in your main function.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361645

Make sure you initialize result to an empty string. Either

char result[2048] = "";

in the caller, or

result[0] = '\0';

at the top of readlist().

Upvotes: 1

Related Questions