请问我想向.txt文件中逐行读取特定字符串,C语言该如何实现?
例如,我想统计以下文本中“edge”的个数,如何逐行读取该字符串,再通过比较统计其个数,C语言如何快速实现?man.txt//node0//edge:{sourcenam...
例如,我想统计以下文本中“edge”的个数,如何逐行读取该字符串,再通过比较统计其个数,C语言如何快速实现?
man.txt
// node 0
// edge: { sourcename: "0" targetname: "7" }
edge: { sourcename: "0" targetname: "12" }
edge: { sourcename: "0" targetname: "23" }
// node 1
// node 2
// node 3
edge: { sourcename: "3" targetname: "0" }
edge: { sourcename: "3" targetname: "1" }
edge: { sourcename: "3" targetname: "2" }
edge: { sourcename: "3" targetname: "9" } 展开
man.txt
// node 0
// edge: { sourcename: "0" targetname: "7" }
edge: { sourcename: "0" targetname: "12" }
edge: { sourcename: "0" targetname: "23" }
// node 1
// node 2
// node 3
edge: { sourcename: "3" targetname: "0" }
edge: { sourcename: "3" targetname: "1" }
edge: { sourcename: "3" targetname: "2" }
edge: { sourcename: "3" targetname: "9" } 展开
1个回答
展开全部
示意代码如下 ,自己写完整吧
#include <stdio.h>
#include <string.h>
FILE *fp;
char str[1024];
int n=0;
fp=fopen("man.txt", "r");
while( fgets(str,sizeof(str),fp) )
{
if ( strncmp( str, "edge", 4 )==0 )
n++;
}
fclose(fp);
printf("n=%d\n", n );
#include <stdio.h>
#include <string.h>
FILE *fp;
char str[1024];
int n=0;
fp=fopen("man.txt", "r");
while( fgets(str,sizeof(str),fp) )
{
if ( strncmp( str, "edge", 4 )==0 )
n++;
}
fclose(fp);
printf("n=%d\n", n );
追问
亲,我想继续问一下,我想提取出每行中targetname: "7"中的像“7”这样的数据,并把它们打印出来,C语言该如何实现呢?再次感谢了!
追答
while( fgets(str,sizeof(str),fp) )
{
if ( strstr( str, "targetname: \"7\"" ) )
printf("%s", str ) ;
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询