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

问题描述 投票:0回答:3

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

这是我的代码的一部分:

    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);
c++ c
3个回答
2
投票

记下你看到了多少个

\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 语言。


2
投票

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

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

0
投票

还有另一种方法可以做到这一点,即使用 while 循环推进指针,直到到达下一行。

int main(){
    int count = 0;
    char buffer;
    
    FILE *fp = fopen("filename", "r");
    
    //not checking for EOF since its assumed there is at least 2 lines
    //this will put you on the second line where you can do your reads
    while(fgetc(fp) != '\n');

    buffer=fgetc(fp)
    while(buffer != '\n'){
        //---------------------------------------------------
        //do whatever you want with the buffer character here
        // im assuming you wanted to calculate the length of the line
        //---------------------------------------------------
        count++;

        buffer=fgetc(fp); //advance a character and go to the top of the loop
    }
    fclose(fp);
}

我知道这个问题很老了(事实上已经有7年了),但我只想提出上面提供的答案的替代答案。

© www.soinside.com 2019 - 2024. All rights reserved.