本文主要是介绍从文件中获取指定字符串源码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
从文件中获取指定字符串源码
#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; }
这篇关于从文件中获取指定字符串源码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!