我如何在 C 中获得由分隔符分隔的标记位置 [英] How do i get the position of tokens seperated by delimeter in C

查看:45
本文介绍了我如何在 C 中获得由分隔符分隔的标记位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件看起来像:

My text file look like:

at:x:25:25:批处理作业守护进程:/var/spool/atjobs:/bin/bash

at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash

avahi:x:109:111:Avahi 的用户:/var/run/avahi-daemon:/bin/false

avahi:x:109:111:User for Avahi:/var/run/avahi-daemon:/bin/false

现在我想获得由分隔符分隔的标记的位置.例如在位置 1、x--位置 2、25--位置 3 等.

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.

现在我的 for 循环不工作 for(int i=0; i

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

}

推荐答案

for(int i = 0;i < str;i++)

你做错了.您正在将 i 与大于 i=0 的地址 进行比较,因此该循环不会启动.我看到当达到 NULL 时你正在打破循环,所以这应该是你 for 循环

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++)

这篇关于我如何在 C 中获得由分隔符分隔的标记位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆