使用 strtok 替换输入文件 C 中的部分字符串

Using strtok to replace parts of a string from input file C

所以我有一个简单的文件 "cat dog chicken rat"。我试图将它加载到一个字符串中并更改其中一个单词。我有

int main(){

    FILE *ifp;
    char *entry;
    char *string;
    char *token;

    ifp=fopen("/home/names.txt", "r");

    entry=malloc(200*sizeof(char));
    while(fgets(entry,75,ifp)){ 
    }

    printf("%s\n",entry);
    token=strtok(entry," ");

    while(token!=NULL){

        if(token=="dog")
            string="bird";

        string=token;
        printf("%s ",string);
        token=strtok(NULL," "); 
    }   
}

然而,当我尝试这样做时,它不会用 "bird" 替换单词 "dog"。我做错了什么?

这将修改原始字符串并将其存储在不同的字符数组中 -

char string[100];                // in your original code allocate memory to pointer string
token=strtok(entry," ");
size_t n;
while(token!=NULL){
  n=strlen(string);                      // calculate string length 
  if(strcmp(token,"dog")==0)             // if "dog" found
     sprintf(&string[n],"bird ");        // add "bird " at that position
  else
     sprintf(&string[n],"%s ",token);    //if doesn't add token 
  token=strtok(NULL," ");
}

注意 - 不要像这样比较字符串 -

    if(token=="dog")

使用 <string.h> 中的函数 strcmp