如何从C语言的第二行读取字符串文件
How to read a string file from second line in 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);
计算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);
}
相关文章:
- 使用新行和不使用新行读取文件
- 如何在c++中从文本文件中逐行读取整数
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- 使用 QT 逐行读取 JSON
- 串行读取更改输入,不读取整行
- 逐行读取文件,并将数据插入变量和数组中
- 我遇到使用 c++ 逐行读取输入文件的问题
- 无法逐行读取.csv文件
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 如何从文件中的特定行读取 (C++)
- 如何将文件逐行读取到矢量中,然后打印矢量
- C++逐行读取文件
- 如何将带有不定条目的行读取到数字数组中?
- 如何逐行读取文件并分隔行组件?
- 串行读取()不会在没有数据接收的情况下返回值
- Arduino 到 C++ 串行读取胡言乱语
- 使用"IF" C++逐行读取文本文件
- 使用字符串流逐行读取文件两次
- C :按行读取txt文件的读数,单词用单词读取,每行的单词不均匀