2012-10-23 173 views
1

我正在写一个小型C程序,它搜索文件中的一串文本,并用另一个字符串替换它,但是在执行此操作时,我不断收到分段错误,并且出于某种原因,我的缓冲区(名为c)在我的fgets调用后是空的。搜索并替换文本

这里是我的代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <dirent.h> 
#include <string.h> 



/* 
*program replaces all strings that match a certain pattern within a file 
*/ 

int main(int argc, char** argv) 
{ 
    // check if there are correct amount of arguments 
    if(argc != 4) 
    { 
      printf("Error, incorrect amount of input arguments!\n"); 
      return 1; 
    } // end if 

    // initializers 
    int i; 
    char* temp; 
    FILE* searchFile; 
    char* c = malloc(sizeof(char)); 
    char* fileName = malloc(sizeof(argv[1])); 
    char** searchWord = malloc(sizeof(argv[2])); 
    char* replaceWord = malloc(sizeof(argv[3])); 

    fileName = argv[1]; 
    *searchWord = argv[2]; 
    replaceWord = argv[3]; 

    // checks to see if searchWord isnt too big 
    if(strlen(*searchWord) > 256) 
    { 
      printf("Error, incorrect amount of input arguments!\n"); 
      return 1; 
    } 

    // opens file 
    searchFile = fopen(fileName,"r+"); 

    // searches through file 
    do 
    { 
      fgets(c, 1, searchFile); 

      i = 0; 
      while(i < strlen(*searchWord)) 
      { 
        printf("search character number %i: %c\n", i, *searchWord[i]);  

        /* 
        * finds number of letters in searchWord 
        * by incrementing i until it is equal to size of searchWord 
        */ 
        if(strcmp(c,searchWord[i])) 
        { 

          i++; 
        } 

        // replaces searchWord with replace word 
        if(i == (strlen(*searchWord))) 
        { 
          printf("inside replace loop\n"); 
          memcpy(searchWord, replaceWord,(sizeof(replaceWord)/sizeof(char))+1); 
          printf("The search term (%s) has been replaced with the term: %s!\n",*searchWord,replaceWord); 
        } 
      } 
    }while(strlen(c) > 0); 

    // closes file 
    fclose(searchFile); 
} 
+0

你为什么只用fgets读一个字符?在这种情况下只需使用fgetc就可以使其更加清晰。 –

+0

与Richard的评论相关,当你只读一个字符时,为什么还要为它分配内存?只需声明'char c;',然后在需要指向该字符的指针时使用'&c'。 –

+0

你应该研究的第二件事是'sizeof'和'strlen'之间的区别。 –

回答

1

你传递一个大小为1至与fgets。但是,fgets函数最多只能读取一个比给定流大小指定的字符数少的字符。所以如果你传递1的大小它读取0个字符。它读取较少的原因是为了留空空行结束字符。

当找到换行符时,在文件末尾或错误处保留换行符(如果有的话),fgets函数会停止读取。所以你需要malloc c是你希望在字符串中加上许多字符加上一个换行符和一个空'行尾'字符。

一些其他的事情要注意。以下两个语句中的第一个首先分配空间来存储文件名,然后将文件名指针指向它。第二再分的文件名指针以指向在包含第一arguement到程序字符串传递:

char* fileName = malloc(sizeof(argv[1])); 
fileName = argv[1]; 

要么只是直接指向文件名指针存在,并且不分配任何内存:

char* fileName = argv[1]; 

或者,如果你确实需要分配的内存,更改第二行复制字符串的内容:

char* fileName = malloc(sizeof(argv[1])); 
strcpy(fileName,argv[1]); 

或者,更容易使用的strdup分配m个emory然后复制内容:

char* fileName = strdup(argv[1]);