从文件中获取指定字符串源码

从文件中获取指定字符串源码
#include 
   
   
    
    
#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
       

void help()
{
	fprintf(stderr, "get string from file   -v1.0.1\t\t\t(c)Tody, 2013"\
			"\nUsage:\n  wAt [-l 
       
       
         ] [-s 
        
          ] [-e 
         
           ] [-B] [-F 
          
            ] [-h]"\ "\n\t-l means the line number specified"\ "\n\t-s means start char location"\ "\n\t-e means end char location"\ "\n\t-B means print 'set value=string'"\ "\n\t-F means you need to specified file to get the string you want" "\n\t-h means this help message"); exit(1); } void oops(char *msg) { fprintf(stderr, "%s", msg); exit(1); } int getString(char *str, int sc, int ec, int isBatch) { char *tmp = str; if (str==NULL) return 1; if (ec !=0 ) *(str+ec)='\0'; if (sc != 0) tmp=tmp+(sc-1); if (isBatch) { printf("set value=%s", tmp); } else printf("%s", tmp); return 0; } int main(int argc, char *argv[]) { FILE *f=NULL; char filename[128]; int isBatch = 0; char buf[80]={'\0'}; int ch; int line = 1; int sc=0; int ec=0; int index = 1; if (argc<2) help(); while((ch = getopt(argc, argv, "l:s:e:hBF:")) != -1) { switch(ch) { case 'l': line = atoi(optarg); if (line == 0) oops("line is not a number"); break; case 's': sc = atoi(optarg); if (sc == 0) oops("start char is not a number"); break; case 'e': ec = atoi(optarg); if (ec == 0) oops("end char is not a number"); break; case 'B': isBatch = 1; break; case 'h': help(); break; case 'F': strncpy(filename, optarg, 128); break; case '?': oops("Error option!"); break; } } if (argc != optind) help(); f = fopen(filename, "rb"); if (f==NULL) oops("File open error"); while(!feof(f)){ fgets(buf, 80, f); if (index == line) { fclose(f); return getString(buf, sc, ec, isBatch); } else index ++; } // printf("Line: %d sc: %d ec: %d", line, sc, ec); fclose(f); return 1; } 
           
          
         
       
      
      
     
     
    
    
   
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值