How do i get the position of tokens seperated by delimeter in C [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 22:18:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!