C 利用strtok, feof 截取字符串

本文介绍了一个简单的C程序,该程序用于读取指定文件,并从中查找包含关键词'cpuset'的行。找到后,程序进一步解析该行以提取特定路径后的字符串。示例展示了如何通过分隔符遍历并获取所需的子字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#cat  /tmp/fff
10:hugetlb:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
9:devices:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
8:perf_event:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
7:cpuacct,cpu,cpuset:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
6:memory:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
4:freezer:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
3:intel_rdt:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
2:blkio:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
1:name=systemd:/hello/06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
#cat gg.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
 int main()
 {
     char filename[] = "/tmp/fff";
     FILE *fp = NULL;
     char newline[128];
     char *keyword = "cpuset";
     char final1[64];
     char *delim = "/";
     char *p = NULL;
     char final2[12];
     int length = 12;

     if((fp = fopen(filename,"r")) == NULL)
     {
         printf("error!");
         return -1;
     }

     while (!feof(fp))
     {
         fgets(newline, 128, fp);

         if (strstr(newline, keyword)) {
            strtok(newline, delim);
            while((p = strtok(NULL, delim))) {
                strcpy(final1, p);
            }
            printf("final1:%s\n", final1);
            break;
         }
     }

    strncpy(final2, final1, length);
    printf("final2:%s\n", final2);
    fclose(fp);
    return 0;
 }
#./gg
final1:06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18

final2:06b11c9967cc

转载于:https://www.cnblogs.com/muahao/p/9002614.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值