- 论坛徽章:
- 0
|
本帖最后由 daodaohu123 于 2012-05-17 18:52 编辑
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char ** str_part(char *str, char *delim)
- {
- char *s = str;
- char *d = delim;
- int n = 0;
- char **p = (char **)malloc(100 * sizeof(char *));
- while((p[n] = strtok(s, d)) != NULL){
- n++;
- s = NULL;
- }
- return p;
- }
- int find_cmp(char **str_group, char *string)
- {
- int ret = 0;
- int n = 0;
- int location = -1;
- char *str = string;
- int len = strlen(str);
- char **str_g = str_group;
- while(str_g[n] != NULL){
- ret = strncmp(str_g[n], str, len);
- if(ret == 0) location = n;
- n++;
- }
- return location;
- }
- char **replace_cmp(char **str_group, int num, char *string)
- {
- char** str_g = str_group;
- int n = 0;
- strcpy(str_g[num], string);
- // strcat(str_g[num], "\0");
- return str_g;
- }
- char *rewrite(char **str_group)
- {
- char **str_g = str_group;
- int n = 0;
- int len = 0;
- char *string = (char *)malloc(100 * sizeof(char));
- while(str_g[n] != NULL){
- len = strlen(str_g[n]);
- strncat(string, str_g[n], len);
- strcat(string, " ");
- n++;
- }
- strcat(string, "\n");
- return string;
- }
- char *extract_str_from_file(char *file, char *keyword)
- {
- FILE *fp;
- char *string = (char *)malloc(100 * sizeof(char));
- char *str = (char *)malloc(100 * sizeof(char));
- fp = fopen(file, "r");
- char **p;
- while(fgets(string, 1024, fp) != NULL ){
- int ret = -1;
- strcpy(str, string);
- p = str_part(string, " ");
- ret = find_cmp(p, keyword);
- if(ret >= 0){
- printf("content of line is :%s", str);
- printf("ret is %d \n", ret);
- fclose(fp);
- return str;
- }
- }
- printf("nothing");
- return "nothing";
- }
- int newfile_rewrite(char * oldfile, char *newfile, char *cmpcontent, char *repcontent)
- {
- char str[1024];
- FILE *fp;
- FILE *dest;
- fp = fopen(oldfile, "r");
- dest = fopen(newfile, "a+");
- while(!feof(fp))
- {
- if(fgets(str, 1024, fp) != NULL){
- if(strcmp(str, cmpcontent)){
- fputs(str, dest);
- }
- else{
- fputs(repcontent, dest);
- }
- }
- }
- fclose(fp);
- fclose(dest);
- return 0;
- }
- int main(int argc, char **argv)
- {
- int n = 0;
- int location;
- char replace_str[]="god";
- char **str_cmp = (char **)malloc(100 * sizeof(char*));
- char *string = malloc(100 * sizeof(char));
- char *delim = " ";
- char **p;
- char *dd = (char *)malloc(100 * sizeof(char));
- string = extract_str_from_file("dd", "me");
- strcpy(dd, string);
- p = str_part(string, delim);
- location = find_cmp(p, "hud");
- replace_cmp(p, location, replace_str);
- str_cmp = replace_cmp(p, location, replace_str);
- char *result = rewrite(str_cmp);
- printf("result is :%s", result);
- printf("dd is :%s", dd);
- newfile_rewrite("dd", "dd_file", dd, result);
- return 0;
- }
复制代码 |
|