1

我有一个可能相当简单的问题。我有一个文件 input.txt,它是:

cat input.txt

testsuite1
test1
summary information of test
FAIL
testsuite2
test1
summary info ya
PASS

我正在编写一个程序,只是为了将这些字符串中的每一个读入变量并进行进一步处理。最好的方法是什么?我目前正在做:

main() {
    FILE *fp;
    char testsuite[100],testname[100],summary[100],result[100];
    fp = fopen("input.txt", "r");
    while(1) {
        if(fgets(testsuite,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        if(fgets(testname,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        if(fgets(summary,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        if(fgets(result,99,fp) == NULL)
        {
            ferror(fp);
            break;
        }
        printf("testsuite: %s testname:%s summary:%s result:%s \n",testsuite,testname,summary,result);
    }


    fclose(fp);
}

有更好的方法吗?我目前面临的问题是,如果 input.txt 甚至包含一个空白行,则空白行会被读入变量。避免它的最佳方法是什么?

谢谢!

4

3 回答 3

2

您应该编写自己的函数来跳过空行(例如调用getline())并使用它来代替fgets()

char *getline(char *buf, int size, FILE *fp)
{
    char *result;
    do {
        result = fgets(buf, size, fp);
    } while( result != NULL && buf[0] == '\n' );
    return result;
}

您现在可以改进该功能以跳过仅包含空格或任何您需要的内容的行。

于 2014-06-11T15:03:03.600 回答
0

您可以在循环之前删除文件的所有空白行。打开后,您解析整个文件并删除空白;)。但这似乎不是最好的方法。

如果你的变量为空,你可以在每个 fget 之后检查你的变量是否为空,在这种情况下,再次 fget 。

希望这会有所帮助。

于 2014-06-11T14:48:37.077 回答
0

如果这样做,一旦循环退出,您将无法使用读取的字符串,因为每个循环都会覆盖缓冲区中的每个字符串。但是,您可以将字符串存储在结构数组中:

    typedef struct {
    testsuite[100];
    testname[100];
    summary[100];
    result[100];
    }test;

    test test_array[2];

    int main(){
    int iIndex=0;
    FILE* fpPtr=NULL;
    fpPtr = fopen("input.txt", "r");
    if(fpPtr==NULL){  //<--- it is very important to check if fopen fails
       perror("fopen");
    }
    for(iIndex=0; iIndex<2; iIndex++){ // 2 because it is the number of elements in test_array
    if(fgets(test_array[i].testsuite,99,fp) == NULL)
     {
        ferror(fp);
        break;
     }
    if(fgets(test_array[i].testname,99,fp) == NULL)
     {
        ferror(fp);
        break;
     }
    if(fgets(test_array[i].summary,99,fp) == NULL)
     {
        ferror(fp);
        break;
     }
    if(fgets(test_array[i].result,99,fp) == NULL)
     {
        ferror(fp);
        break;
     }
    }

  }

您可以通过检查位置 0 处的换行符来检测空行: fgets(cBuffer, sizeof(cBuffer), fpPtr);

//<-- if the file was created on windows, check for '\r' instead, since a new line in windows is \r\n
    if(cBuffer[0]=='\n')
    { 
      printf("blank line"\n);
    }
于 2014-06-11T15:07:16.067 回答