Annotation of OpenXM/src/util/oxreplace.c, Revision 1.2
1.2 ! takayama 1: /* $OpenXM: OpenXM/src/util/oxreplace.c,v 1.1 2003/03/26 04:45:37 takayama Exp $ */
1.1 takayama 2: /* cf. fb/src/misc/nan-tfb2.c */
3: #include <stdio.h>
4: #include <time.h>
5: char *readAsString(FILE *fp) {
6: static char *s = NULL;
7: static int size= 102400;
8: int p = 0;
9: char *s2;
10: int c;
11: if (s == NULL) {
12: s = (char *) malloc(size);
13: if (s == NULL) {
14: fprintf(stderr,"no more memory.\n"); exit(10);
15: }
16: }
17: s[0] = 0;
18: while ((c=fgetc(fp)) != EOF) {
19: s[p++] = c; s[p] = 0;
20: if (p >= size-2) {
21: s2 = s;
22: size = 2*size;
23: s = (char *) malloc(size);
24: if (s == NULL) {
25: fprintf(stderr,"no more memory.\n"); exit(10);
26: }
27: strcpy(s,s2);
28: free(s2);
29: }
30: }
31: return s;
32: }
33:
34: matches(char *word,char *s,int j) {
35: int i;
36: for (i=0; i<j; i++) {
37: if (word[i] != s[i]) return 0;
38: }
39: return 1;
40: }
41: main(int argc, char *argv[]) {
42: int i;
43: char *old = NULL;
44: char *new = NULL;
45: if (argc < 2) {usage(); exit(0); }
46: for (i=1; i<argc; i++) {
47: if (strcmp(argv[i],"--old") == 0) {
48: old = argv[i+1]; i++;
49: } else if (strcmp(argv[i],"--new") == 0) {
50: new = argv[i+1]; i++;
51: } else if (strcmp(argv[i],"--f") == 0) {
52: fprintf(stderr,"--f option (rule file) has not yet been implemented.\n");
53: exit(10);
54: }else {
55: if ((old != NULL) && (new != NULL)) {
56: replaceOneWord(argv[i],old,new);
57: }else{
58: fprintf(stderr,"--old and --new option or --f option are not given.\n");
59: usage();
60: exit(10);
61: }
62: }
63: }
1.2 ! takayama 64: exit(0);
1.1 takayama 65: }
66:
67: #define DEBUG 1
68:
69: replaceOneWord(char *fname,char *old, char *new) {
70: FILE *fp;
71: FILE *fpOrig;
72: char *s;
73: char *fnameBackup;
74: char *comm;
75: int i;
76: #ifdef DEBUG
77: fprintf(stderr,"fname=%s, old=%s, new=%s\n",fname,old,new);
78: #endif
79: fp = fopen(fname,"r");
80: if (fp == NULL) {
81: fprintf(stderr,"File %s is not found.\n",fname);
82: return -1;
83: }
84: fclose(fp);
85:
86: fnameBackup = (char *)malloc(strlen(fname)+200);
87: comm = (char *)malloc(strlen(fname)+300);
88: if (fnameBackup == NULL) {
89: fprintf(stderr,"No more memory.\n"); exit(10);
90: }
91: sprintf(fnameBackup,"%s.%ld.oxreplace-tmp.old",fname,(long) time(NULL));
92: sprintf(comm,"cp %s %s",fname,fnameBackup);
93: system(comm);
94:
95: fpOrig = fopen(fnameBackup,"r");
96: fp = fopen(fname,"w");
97: s = readAsString(fpOrig);
98: for (i=0; i<strlen(s); i++) {
99: if (!matches(old,s+i,strlen(old))) {
100: fputc(s[i],fp);
101: }else{
102: fprintf(fp,"%s",new);
103: i += strlen(old)-1;
104: }
105: }
106: fclose(fp); fclose(fpOrig);
107: free(comm); free(fnameBackup);
108: return 0;
109: }
110:
111:
112: usage() {
113: fprintf(stderr,"oxreplace [--old oword --new nword --f rule_file_name] \n");
114: fprintf(stderr," [file1 file2 ... ] \n");
115: }
116:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>