我编写了一个程序来从文件(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()无法正常工作。有人可以帮我吗?
查看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++;
}
}
这可以通过fgets完成。来自man7.org:请参见fgets
fgets()
函数应从bytes
读取stream
到数组中在我们的情况下,由s
指向line
,直到读取n−1 bytes
,或者读取<newline>
并将其传送到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);
}