使用c从文件中读取特定范围的行

时间:2012-06-22 15:03:48

标签: c linux file file-io

我在文件中有以下内容:

hhasfghgsafjgfhgfhjf
gashghfdgdfhgfhjasgfgfhsgfjdg
jfshafghgfgfhfsghfgffsjgfj
.
.
.
.
.
startread
hajshjsfhajfhjkashfjf
hasjgfhgHGASFHGSHF
hsafghfsaghgf
.
.
.
.
.
stopread
.
.
.
.
.
.
jsfjhfhjgfsjhfgjhsajhdsa
jhasjhsdabjhsagshaasgjasdhjk
jkdsdsahghjdashjsfahjfsd

我需要使用ac代码读取startread的下一行到stopread的上一行的行,并将其存储到字符串变量(当然使用\n每一行都打破了。我怎样才能实现这一目标? 我使用过fgets(line,sizeof(line),file);但它从头开始阅读。由于文件是由另一个C代码写的,因此我没有确切的行号来启动和停止读取。但是有一些标识符startreadstopread可以识别开始阅读的位置。操作平台是linux。提前谢谢。

2 个答案:

答案 0 :(得分:1)

使用strcmp()检测startreadstopread。忽略读取"startread"之前读取的所有行,然后存储所有行,直到读取"stopread"

/* Read until "startread". */
char line[1024];
while (fgets(line, sizeof(line), file) &&
       0 != strcmp(line, "startread\n"));

/* Read until "stopread", only if "startread" found. */
if (0 == strcmp(line, "startread\n"))
{
    while (fgets(line, sizeof(line), file) &&
           0 != strcmp(line, "stopread\n"))
    {
        /* Do something with 'line'. */
    }
}

答案 1 :(得分:0)

    #define MAX_BUF_LEN 1000    
    int flag=0;
    while(fgets(buf, MAX_BUF_LEN, file) != NULL){
       if(strncmp(buf, "startread", strlen("startread")) == 0){
          flag=1;
       }
       else if (strncmp(buf, "stopread", strlen("stopread")) == 0){
          flag=0;
       }

       if(flag){
          strncpy(line, buf, strlen(buf));
         // strncat(line, '\n', strlen('\n'));
       }

    // that's all!
    }
    fclose(file);

这应该有效。

相关问题