如果遇到逗号(,),则跳转到文件中的下一行,然后继续在C中搜索 [英] Jump to next line in a file, if a comma ( , ) is encountered, and continue the search in C

查看:373
本文介绍了如果遇到逗号(,),则跳转到文件中的下一行,然后继续在C中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建防火墙模拟器。显然我会添加规则集。所以我使用.txt文件作为规则。示例txt记录:



I was building a firewall simulator sort of thing. Obviously I will add rule set.So I'm using a .txt file for my rules. Sample txt records :

HOST_IP, HOST_PORT, DEST_IP, DEST_PORT
192.168.1.100, 32, 127.0.0.1, 567
192.168.1.101, 32, 127.0.0.1, 09
192.168.1.102, 32, 127.0.0.1, 64
192.168.1.103, 32, 127.0.0.1, 56



所以我希望的是,如果文件正在搜索Host ip,那么它应该首先搜索所有主机IP。同样,一旦遇到逗号(,),指针就会跳转到下一行并检查第二行中的IP地址(在第一个逗号之前)。如果找到,它必须返回,否则它必须在遇到逗号(,)后跳转到下一行并在下一行搜索IP。



我尝试过:




So what I wish for is that, if the file is searching Host ip, so it should search all the host IPs first. As in, as soon as a comma ( , ) is encountered, the pointer jumps to the next line and checks the IP address (before first comma) in second line. If found, it must return, else it must jump to next line after it encounters a comma ( , ) and search for the IP in the next line.

What I have tried:

#include <stdio.h>
#include <stdlib.h>
   main( )
   {
     FILE *fp;
     char c[20],*string;
     fp = fopen("test.txt", "r");
     if (fp == NULL)
		printf("File doesn't exist\n");
     else {
      do {
       fscanf(fp,"%s",string);
	t=getc(fp);
	
	
		if(strcmp(string,c)){printf("Found");fclose(fp);}
		if(t==",")//here i need to jump to next line

        	 putchar(c); /* display it on the monitor
       		*/
       	
	} while (c != EOF); /* repeat until EOF (end of file)
     */
     }
    fclose(fp);
   }

推荐答案

请勿使用 fscanf ,但请使用 fgets 一次读取一行。然后,您可以将该行标记(使用 strtok )来检查各个字段。
Don't use fscanf, but use fgets to read one line at a time. You can then tokenise the line (using strtok) to check individual fields.


这篇关于如果遇到逗号(,),则跳转到文件中的下一行,然后继续在C中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆