如何从C中的第二行读取字符串文件?

时间:2013-05-04 17:10:56

标签: c++ c

此代码读取文件中的字符并计算字符长度。我如何从第二行读取并忽略第一行的读取?

这是我的代码的一部分:

    int lenA = 0;
    FILE * fileA;
    char holder;
    char *seqA=NULL;
    char *temp=NULL;

    fileA=fopen("d:\\str1.fa", "r");
    if(fileA == NULL) {
    perror ("Error opening 'str1.fa'\n");
    exit(EXIT_FAILURE);
    }

    while((holder=fgetc(fileA)) != EOF) {
    lenA++;
    temp=(char*)realloc(seqA,lenA*sizeof(char));
    if (temp!=NULL) {
        seqA=temp;
        seqA[lenA-1]=holder;
    }
    else {
        free (seqA);
        puts ("Error (re)allocating memory");
        exit (1);
    }
}
cout<<"Length seqA is: "<<lenA<<endl;
fclose(fileA);

2 个答案:

答案 0 :(得分:1)

计算一下你看过多少\n,以及==1从第二行读取的时间。

    int line=0;
    while((holder=fgetc(fileA)) != EOF) {
     if(holder == '\n') line++;
     if(holder == 1) break; /* 1 because count start from 0,you know */
    }
    if(holder == EOF) {
     //error:there's no a 2nd
    }       
   while((holder=fgetc(fileA)) != EOF) { 
    // holder is contents begging from 2nd line
   }

您可以使用fgets()

使其更简单

拨打一个电话并忽略它(不要丢弃结果值,以便进行错误检查);

拨打第二个电话,并乞求阅读。

注意:我在这里考虑使用C语言。

答案 1 :(得分:0)

关于最后一个答案,有一个小错误。 我纠正了,这是我的代码:

#include <stdio.h>
#include <stdlib.h>

#define TEMP_PATH "/FILEPATH/network_speed.txt"

int main( int argc, char *argv[] )
{
    FILE *fp;
    fp=fopen(TEMP_PATH, "r");

    char holder;

    int line=0;
    while((holder=fgetc(fp)) != EOF) {
        if(holder == '\n') line++;
        if(line == 1) break; /* 1 because count start from 0,you know */
    }
    if(holder == EOF) {
        printf("%s doesn't have the 2nd line\n", fp);
        //error:there's no a 2nd
    }       
    while((holder=fgetc(fp)) != EOF && (holder != '\n' )) { 
        putchar(holder);
    }
    fclose(fp);
}
相关问题