hillz hillz - 5 months ago 54
C Question

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

I have a text file like this:

/www/test.php = 24323

strtok(myfile," = ")
it only prints the first occurrence which is
, how can I print the second occurrence which is


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


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.


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");