【问题标题】:Read data values from text file along with number of rows and columns in C从文本文件中读取数据值以及 C 中的行数和列数
【发布时间】:2017-05-12 10:59:18
【问题描述】:

我有一个 .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值的情况下,把这段代码泛化到任何数据文件。

注意:不同数据文件之间的列数不变。

【问题讨论】:

  • fscanf 返回一个值.....

标签: c arrays file


【解决方案1】:

您必须自己计算行数(例如this),然后将文件指针倒回到文件的开头,以实际解析它,因为您找到了N。

要将指针重置为文件的开头,请执行以下操作:

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

相关代码可见here。

【讨论】:

  • 您愿意在这里写下完整的答案,而不是把我重定向到另一个链接吗?
  • 我已尽力回答@RD017,希望对您有所帮助! =)
【解决方案2】:
/* 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;  
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多