나는 파일 내의 텍스트 문자열을 찾고 다른 문자열로 바꾸는 작은 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를 사용하면됩니다. –
리차드의 한마디 한마디 만 읽었을 때, 왜 그걸 위해 메모리를 할당해야합니까? 'char c;를 선언하고 그 문자에 대한 포인터가 필요할 때'& c'를 사용하십시오. –
두 번째로 살펴볼 것은'sizeof'와'strlen'의 차이점입니다. –