问题
My text file look like:
at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash
avahi:x:109:111:User for Avahi:/var/run/avahi-daemon:/bin/false
Now i want to get the position of tokens seperated by delimeters. like eg at-position 1, x--position 2, 25--position 3 and so on.
Now my for loop is not working for(int i=0; i
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
char *str, *saveptr;
char ch[100];
char *sp;
FILE *f;
int j;
char searchString[20];
char *src;
f = fopen("passwd", "r");
if (f == NULL)
{
printf("Error while opening the file");
//exit(1);
}
char *dup;
while (fgets(ch, sizeof ch, f)!= NULL)
{
/*printf("%s\n", ch); */
dup = strdup(ch);
for (j = 1, str = ch; ; j++, str= NULL)
{
for(int i = 0;i < str;i++)
{
char *token = strtok_r(str, ":", &saveptr);
if (token == NULL)
break;
src[i] = token;
printf("%s", src[i]);
}
//printf("%s---\n---", token);
//printf("%s",token);
if (strstr(token, argv[2]) != NULL)
{
printf(dup);
}
}
}
fclose(f);
}
回答1:
for(int i = 0;i < str;i++)
You are doing it wrong. You are comparing i with an address
which is larger than i=0 so this loop won't start. I see you are breaking the loop when NULL
is reached, so this should be you for loop
for(int i = 0; ;i++)
来源:https://stackoverflow.com/questions/19354511/how-do-i-get-the-position-of-tokens-seperated-by-delimeter-in-c