zoukankan      html  css  js  c++  java
  • C 利用strtok, feof 截取字符串

    #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
    ", final1);
    			break;
    		 }
         }
    
    	strncpy(final2, final1, length);
       	printf("final2:%s
    ", final2);
    	fclose(fp);
    	return 0;
     }
    
    
    #./gg
    final1:06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
    
    final2:06b11c9967cc
    
  • 相关阅读:
    处理emacs-org模式TODO的一个脚本
    MYSQL 数据类型
    Redis命令学习-Transaction(事务)
    成都青羊考场科目二考试分享
    地图入门_坐标系统
    microsoft SQL server,错误2
    搭建个人博客 方式2 使用jekyll
    WIN10 10招
    java正則表達式总结
    图解hdu5301Buildings
  • 原文地址:https://www.cnblogs.com/muahao/p/9002614.html
Copyright © 2011-2022 走看看