逐行读取文件,读取第一个字符串,如果匹配则使用其余行,否则移动到下一行

时间:2018-01-10 23:15:35

标签: c fgets strtok

对于C来说,我很遗憾是一个完整的新手。我正在尝试读取一个格式化的文本文件

one two three
two one three
three one 

我需要读取一行中的第一个字符串(所以如果第一行是"一个",那么我做一个与变量的比较。如果匹配那么我需要使用其余的字符串,所以如果匹配字符串1我需要使用" 2"和#34; 3"(分别作为他们自己的字符串)。 如果没有匹配,我会转到下一行,依此类推。

这是我到目前为止的代码,但它似乎没有用。在评论中我认为代码正在做什么。

char temp[] = "three";
while(!feof(file)){ //Go until end of file is reached
    fgets(line, 100, file); //Grab the line
    string_token = strtok(line, " "); //Tokenize the line 
    strcpy (compare_to, string_token); //Copy first token into a string variable
    if (strcmp(compare_to, temp) == 0){ //Compare string with a predefined temp variable
        while (string_token != NULL) { //If it was a match then we go until tokens end (which would be end of the line from a file)
            printf("%s has the following: %s\n", temp,compare_to );   
            string_token = strtok(NULL, " ");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

  

逐行读取文件,读取第一个字符串,如果匹配则使用其余行,否则移至下一行

在所有情况下,代码都需要读取整行 - 这只是一个如何使用输入的问题。

请勿使用此problematic code

// while(!feof(file)){
//  fgets(line, 100, file);

相反

while(fgets(line, sizeof line, file)) {

现在解析字符串,将\ n添加到分隔列表。

  int count = 0;
  string_token = strtok(line, " \n");
  // compare the the i'th `compare_to[i]` or 
  // what ever fulfills "then I do a comparison with a variable"
  if (string_token != NULL && strcmp(compare_to[i], string_token) == 0){
    printf("<%s>\n", string_token );   
    string_token = strtok(NULL, " \n");
    count++; 
  }
}

答案 1 :(得分:0)

你可以这样做:

char first_str[128];
while(fgets(line, 100, file) != NULL)
{
    sscanf(line, "%s", first_str);
    if(strcmp(first_str, "your_str") == 0)
    {
        // match
        // so use result of the line
    }
}

基本上,您正在阅读整行,然后使用sscanf检查第一个字符串,然后根据您的条件继续进行。

编辑:确保您的数组长度足以容纳字符串。

相关问题