简体   繁体   English

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

[英]How to read a string file from second line in C?

This code reads characters in a file and calculates length of characters. 此代码读取文件中的字符并计算字符长度。 How i can read from second line and ignore read from first line? 我如何从第二行读取而忽略从第一行读取?

this is part of my code: 这是我的代码的一部分:

    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);

Make a counter of how many \\n you have seen,and when ==1 goto read from 2nd line. 记下您已经看过多少\\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
   }

You can make it more simple by using fgets() : 您可以使用fgets()使它更简单:

Make one call and ignore it(by don't discard the result-value,for error-checking); 进行一次呼叫并忽略它(不丢弃结果值,以进行错误检查);

Make second call, and begging reading from this. 拨打第二个电话,并恳求阅读。

NOTE: I'm considering C language here. 注意:我在这里考虑使用C语言。

There is a tiny mistakes about the last answer. 最后一个答案有一个小错误。 I corrected and here is my code: 我已更正,这是我的代码:

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM