我有一个.txt
格式的数据文件,包含7行和4列。
我使用以下代码来读取这些值:
#include<stdio.h>
#include<math.h>
int main()
{
int N=7, i;
double x[7], y[7], p[7], q[7];
FILE *f1;
f1=fopen("data.txt","r");
for(i=0;i<N;i++)
fscanf(f1,"%lf %lf %lf %lf", &p[i], &q[i], &x[i], &y[i]);
fclose(f1);
}
这里N是数据文件中的行数,我事先知道。
有没有办法读取数据文件中的行数,这样我就可以在不知道N值的情况下为任何数据文件推广这段代码。
注意:不同数据文件之间的列数不会改变。
答案 0 :(得分:0)
您必须自己计算行数(例如this),然后将文件指针倒回到文件的开头,实际解析它,现在您找到了N
。< / p>
要将指针重置为文件的开头,请执行以下操作:
fseek(fptr, 0, SEEK_SET);
另一种方法是找出数据的大小并进行一些计算,如下所示:
% Read the vector size
d = fread (fid, 1, 'int');
vecsizeof = 1 * 4 + d * 4;
% Get the number of vectrors
fseek (fid, 0, 1);
a = 1;
bmax = ftell (fid) / vecsizeof;
b = bmax;
if nargin >= 2
if length (bounds) == 1
b = bounds;
elseif length (bounds) == 2
a = bounds(1);
b = bounds(2);
end
end
assert (a >= 1);
if b > bmax
b = bmax;
end
if b == 0 | b < a
v = [];
fclose (fid);
return;
end
% compute the number of vectors that are really read and go in starting positions
n = b - a + 1;
fseek (fid, (a - 1) * vecsizeof, -1);
答案 1 :(得分:0)
/* count the number of rows in the given text table */
#include<stdio.h>
int main()
{
int count = 0;
FILE* ptr = fopen("D:\\test.txt","r");
if (ptr==NULL)
{
printf("no such file.");
return 0;
}
/* Assuming that test.txt has content in below
format with 4 row and 3 column
NAME AGE CITY
aaa 21 xxxxx
bbb 23 yyyyy
ccc 24 zzzzz
ddd 25 qqqqqq */
char* buffer[100];
while (fscanf(ptr,"%*s %*s %s ",buffer)==1)
{
count++;
//printf("%s\n", buffer);
}
// if there are column name present in the table in first row
printf("count = %d", (count-1));
return 0;
}