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\n", final1);
break;
}
}
strncpy(final2, final1, length);
printf("final2:%s\n", final2);
fclose(fp);
return 0;
}
#./gg
final1:06b11c9967cc0e106f5f4673246f671aa7388f623f58b250d9d9cb0f8c0f2b18
final2:06b11c9967cc
muahao@aliyun.com