我正在编写一个小型 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);
}