hillz hillz - 25 days ago 10
C Question

C Program - How to get the second occurrence in strtok()?

I have a text file like this:

/www/test.php = 24323


with
strtok(myfile," = ")
it only prints the first occurrence which is
/www/test.php
, how can I print the second occurrence which is
24323
?

NEW PROBLEM:

char * name;
char *def_size;
name = strtok (line," = ");
def_size = strtok(NULL, " = ");
stat(name, &st);
if (st.st_size != def_size) {
printf("File size doesn't match\n");
}


When I compile that, I get:


test.c: In function ‘main’: test.c:23:24: warning: comparison between
pointer and integer
if (st.st_size != def_size) {
^~


How do I fix this ? Sorry I'm really new to C programming

Answer

You change the first argument of strtok to NULL. It would look like this:

strtok(NULL, " = ");

Of course, you would still have to keep your call to strtok(myfile, " = "); but any subsequent calls to strtok with NULL as the first argument will continue from the last point of the previously specified string.

Example:

printf("%s", strtok(myfile, " = ");     // prints "/www/test.php"
printf("%s", strtok(NULL, " = ");       // prints "24323"

You also cannot compare a string to an integer. You need to use atoi like so:

if (st.st_size != atoi(def_size) {
    printf("File size doesn't match\n");
}
Comments