【需求场景】
之前的shell脚本中配寄存器调用的是./ads w <devsel> <reg> <val>,现在工具换了,工具名和参数以及使用方式都变了,变成了echo "<devsel> <reg> <val>" > /sys/class/ti-spi/ads/write。但是,之前写的那些脚本散落在各个目录下手动一行行改太费劲了,就算有notpad++这类支持列编辑模式的软件,改起来也得一天,还易错,更重要的是,手疼!于是乎,想到了写个程序干这件事,程序员嘛,就要有这种懒惰的智慧。
【思路原理】
一切皆文件,我把它一行行读回来,查找当前行中有没有要替换的,有则把它抠掉,剩余的再前接一个后接一个。但这里还需要注意,原shell脚本中字符串之间的空格个数不尽相同,有的甚至使用tab键,如果生硬的搜索某个定死的长串,则不能做到很好的兼容性。
【代码】
#include <stdio.h> #include <stdlib.h> #include <string.h> #define LINE 1024 /* 将字符串腰斩 */ char *strncpy_waist(char *str, int offset, int len) { int i=0; for (i=0;i<len;i++) { *(str + i) = *(str + i + offset); } while (*(str + i)) { *(str + i) = ' '; i++; } printf("%s", str); return str; }
/* 这种做法就不能做到对空格的兼容性 */ int ReadData1(FILE *fp, char *buf, char *child) { char *ret = fgets(buf, LINE, fp);//?????buf if (ret == NULL ) { return -1; } int len = strlen(child); int len1 = strlen(buf); if ( 0 == strncmp(buf,child, len) ) { strncpy_waist(buf,len,len1 - len); return 0; } else { return 1; } } void someprocess1(char *buf, char *before, char *after) { char buf1[LINE]={0}; int len = strlen(buf); strncpy(buf1,buf,len-1); sprintf(buf, "%s %s %s" , before, buf1, after); } int ReadData(FILE *fp, char *buf, char *child) { char *ret = fgets(buf, LINE, fp);//?????buf if (ret == NULL ) { return -1; } char sample1[20]={0}; char sample2[20]={0}; char cur1[20]={0}; char cur2[20]={0}; char buf1[LINE]={0}; strcpy(buf1,buf); memset(buf,0,strlen(buf)+1); sscanf(child,"%s%s",sample1,sample2); sscanf(buf1,"%s%s",cur1,cur2); if ( 0 == strcmp(sample1,cur1) && 0 == strcmp(sample2,cur2) ) { sscanf(buf1,"%*s%*s%[^ ]",buf); return 0; } else { strcpy(buf,buf1); return 1; } } void someprocess(char *buf, char *before, char *after) { char buf1[LINE]={0}; strcpy(buf1,buf); sprintf(buf, "%s %s %s " , before, buf1, after); } int write_into_new(FILE *fp, char *buf) { int len = strlen(buf) + 1; fwrite(buf,len,1,fp ); return 0; } int main(int argc, char* argv[]) { FILE *fp, *fp_new; char *buf, filename_new[20]={0}; int p; sprintf(filename_new, "%s_xxg", argv[1]); if ((fp=fopen(argv[1], "r"))==NULL) { printf("open file error!! "); return -1; } if ((fp_new=fopen(filename_new, "w"))==NULL) { printf("create file error!! "); return -1; } buf=(char*)malloc(LINE*sizeof(char)); while(1) { p=ReadData(fp, buf, "./ads w");// if(p == -1)//到文件结尾了 break; if(p == 0) { someprocess(buf, argv[2], argv[3]); } write_into_new(fp_new, buf); } return 0; }