【问题标题】:In file reading, how to skip the Nth first lines在文件读取中,如何跳过第 N 行
【发布时间】:2020-06-16 07:03:16
【问题描述】:

我编写了一个程序来从文件 (input.xyz) 中读取分子的 X、Y 和 Z 坐标并执行一些任务。然而, 我希望我的程序跳过前两行作为我的输入文件 结构如下:

3 
water 
O      -0.73692879      -1.68212007      -0.00000000 
H       0.03427635      -1.68212007      -0.59075946 
H      -1.50813393      -1.68212007      -0.59075946

我在我的代码中使用了以下部分

fptr = fopen(filename, "r");
fseek(fptr,3,SEEK_SET);
for(i=0;i<Atom_num;i++)
{
   X[i] = Y[i] = Z[i] = 0;
   fscanf(fptr,"%2s%lf%lf%lf",Atom[i].symbol,&X[i],&Y[i],&Z[i]);
   printf("%2s\t%lf\t%lf\t%lf\n",Atom[i].symbol,X[i],Y[i],Z[i]);
}
fclose(fptr);

其中 Atom_num 是 input.xyz 的第一行

但是,printf 显示以下输出

at  0.000000    0.000000    0.000000 
er  0.000000    0.000000    0.000000  
O   -0.736929   -1.682120   -0.000000

我不知道为什么 fseek() 不起作用。 谁能帮我解决这个问题?

【问题讨论】:

  • 您可以使用fgets 读取每一行并使用sscanf 提取其信息。这样,您可以简单地跳过任意多行。不要使用fseek
  • printf之前添加if(i &gt; 1)?
  • fseek 不会将文件指针定位到第 n 行,而是定位到第 n 个字节。

标签: c fseek


【解决方案1】:

看fseek()的签名:

int fseek(FILE *stream, long int offset, int whence)

尤其是在offset

的定义中

offset - 这是要偏移的字节数。

所以当你这样做时:

fseek(fptr,3,SEEK_SET);

您只需跳过输入文件中的 3 个字节。

你想做的是这样的:

char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
    if (count == lineNumber)
    {
        //Your code regarding this line and on, 
          or maybe just exit this while loop and 
          continue reading the file from this point.
    }
    else
    {
        count++;
    }
}

【讨论】:

  • 或者,考虑使用(在具有它们的实现上)getline(3)readline(3)
  • 我想知道 line[256] 是什么意思?是指一行 256 个字符吗?
  • 是的,这只是一些随机值。我假设单行不超过 256 个字符,所以我制作了缓冲区来读取这个大小的行。
【解决方案2】:

-- fgets() 方法--

这可以通过 fgets 来完成。 来自 man7.org:见这里fgets

fgets() 函数应将 bytesstream 读入数组 由s 指向,在我们的例子中由line 指向,直到n−1 bytes 被读取,或者&lt;newline&gt; 被读取并传输到line,或者遇到end-of-file, EOF 条件。然后字符串以null 字节结束。

#include <stdio.h>
#define LINES_TO_SKIP   3
#define MAX_LINE_LENGTH 120

int main () {
   FILE *fp;
   char line[MAX_LINE_LENGTH];  /*assuming that your longest line doesnt exceeds MAX_LINE_LENGTH */
   int line_c = 0;

   /* opening file for reading */
   fp = fopen("file.txt" , "r");
   if(fp == NULL) 
   {
      perror("Error opening file");
      return(-1);
   }
   
   while(( fgets (line, MAX_LINE_LENGTH, fp)!=NULL )
   {
      if(line_c < LINES_TO_SKIP)
      {
        ++line_c;
        puts("Skiped line");
      }
      else
      {
        /*
         ... PROCESS The lines...
       */
      } 
   }
   
   fclose(fp);
   
   return(0);
}

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多