C从文件中读取字符串内容并比较相等

我正在阅读文件中的内容,我期待找到一个特定的值,比如说“伦敦”。 为此我正在阅读内容,用“\ n”标记它,然后使用“strcmp”将每个值与“london”进行比较。

但我想我仍然不明白C如何存储数据并进行比较,因此下面的代码不能像我期望的那样工作。 我想我在这里缺少一些C的基础知识,请帮忙:

测试命令行:

./myprogram datafile.txt "london" 

INPUT datafile.txt:

 london manchester britain ... 

代码myprogram.c:

 int main(int argc, char **argv) { FILE* fl; char st1[2000]; char * buffer = 0; long length; fl = fopen (argv[1], "r"); //the data file content is shown above if (fl){ fseek (fl, 0, SEEK_END); length = ftell (fl); fseek (fl, 0, SEEK_SET); buffer = malloc (length+1); if (buffer){ //fread (buffer, 1, length, fl); fread(buffer, sizeof(char), length, fl); buffer[length] = '\0'; } fclose (fl); }else{ printf("data file not found"); return -1; } //firstly let's compare the value passed by command line with "london" strcpy(st1, argv[2]); if(strcmp(st1,"london")==0) printf("equals\n"); //as expected, I get "equals" printed else printf("unequal\n"); //now let's compare the values extracted from the data file, char* entity = strtok(buffer, "\n"); while (entity != NULL) { strcpy(st1, entity); //copy the value from the char pointer entity to the char array st1 so we can compare with other strings printf("%s\n", st1); //this prints london, .... if(strcmp(st1,"london")==0) printf("equals\n"); //I was expecting this.. else printf("unequal\n"); //but i got this... entity = strtok(NULL, "\n"); } return 0; 

}

我期待上述程序的输出为:

 equals london equals manchester unequal britain unequal ... 

但我不明白我为什么会这样

 equals london unequal <=============== why and how to fix? manchester unequal britain unequal ... 

我应该如何更改它,以便从文件中读取的值“london”等于“london”的实际“字符串”?

非常感谢

我尝试以下的东西,并用strncpy替换strcpy的调用。 你最初的问题是st1变量末尾的’\ 0’。 所以你可以这样做:

  while (entity != NULL) { strncpy(st1, entity,strlen(entity)-1); //copy the value from the char pointer entity to the char array st1 so we can compare with other strings printf("%s\n", st1); //this prints london, .... if(!strcmp(st1,"london")) printf("equals\n"); //I was expecting this.. else printf("unequal\n"); //but i got this... entity = strtok(NULL, "\n"); } 

或者另一个解决方案是将’\ 0’置于st1的末尾,如下所示:

 strcpy(st1, entity); st1[strlen(entity)-1] = '\0'; 

我测试了两者,它正在工作。