如何从C语言的第二行读取字符串文件

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

本文关键字:二行 读取 文件 字符串 语言      更新时间:2023-10-16

这段代码读取文件中的字符并计算字符长度。我怎么能从第二行读取而忽略从第一行读取?

这是我代码的一部分:

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

计算n的数目,以及==1何时从第2行开始读取

    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():

来使它更简单

进行一次调用并忽略它(通过不丢弃result-value,用于错误检查);

进行第二次调用,并请求读取。

注意:这里我考虑的是C语言

最后一个答案有一点小错误。我更正了,下面是我的代码:

#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 linen", fp);
        //error:there's no a 2nd
    }       
    while((holder=fgetc(fp)) != EOF && (holder != 'n' )) { 
        putchar(holder);
    }
    fclose(fp);
}