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

时间:2015-07-15 12:49:26

标签: c

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

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

TEST COMMAND LINE:

./myprogram datafile.txt "london"

INPUT datafile.txt:

london
manchester
britain
...

CODE 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”的实际“字符串”?

非常感谢

1 个答案:

答案 0 :(得分:0)

我尝试以下操作,并将a[class^="PIN"]{ top: 20px!important ;} 的调用替换为strcpy。你最初的问题是&#39; \ 0&#39;在strncpy变量的末尾。所以你可以这样做:

st1

或另一种解决方案是将&#39; \ 0&#39;你自己在 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"); } 这样的结尾:

st1

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