c - 如何获取C中分隔字符串的位置

标签 c

如何获取分隔字符串的位置?

我的文本文件看起来像

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

beagleindex:x:110:112:User for Beagle indexing:/var/cache/beagle:/bin/bash

我的 C 代码看起来像

#include<stdio.h>


int main(int argc, char *argv[])
{
char *str, *saveptr;
char ch[100];
char *sp;
FILE *f;
int j;
char searchString[20];
char *pos;
f = fopen("passwd", "r");
if (f == NULL)
{
    printf("Error while opening the file");
}
while (fgets(ch, sizeof ch, f)!= NULL)
{
    /*printf("%s\n", ch); */

    for (j = 1, str = ch; ; j++, str= NULL)
    {
         char *token = strtok_r(str, ": ", &saveptr);
         if (token == NULL)
             break;
         //printf("%s---\n---", token);
         printf("%s",token);

     }    


 }  


fclose(f);

最佳答案

好吧,使用 strtok(str, ": ", 会在空格和冒号上分割字符串,这可能不是您想要的。此外,strtok 将多个连续的分隔符视为单个分隔符(因此它永远不会在两个冒号之间返回空字符串),这不是您解析 passwd 所需的。

相反,您可能只想使用 strchr:

while (fgets(ch, sizeof ch, f)!= NULL) {
    char *token, *end;
    for (j = 1, token = ch; token; j++, token = end) {
        if ((end = strchr(token, ':'))) *end++ = 0;
        ...do something with token and j

关于c - 如何获取C中分隔字符串的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331525/

相关文章:

c - 没有初始化点的指针在哪里?

.net - 按启动时间 PowerShell 过滤进程

c - 用于任意精度算术的 GCD 算法

android - fork() 返回现有进程的 pid

c - 右页眉组织

c - 如何检查命令行参数是否为整数

c - 使用嵌入式C测试环境缺少头文件

c++ - 如何标记 C 字符串的结尾?

C-两个指针之间的转换行为

C - 终止的好方法