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);
}
你爲什麼只用fgets讀一個字符?在這種情況下只需使用fgetc就可以使其更加清晰。 –
與Richard的評論相關,當你只讀一個字符時,爲什麼還要爲它分配內存?只需聲明'char c;',然後在需要指向該字符的指針時使用'&c'。 –
你應該研究的第二件事是'sizeof'和'strlen'之間的區別。 –