1

I have a data file in .txt format with 7 rows and 4 columns. I am using following code to read these values:

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

Here N is the number of rows in the data file, which I know in advance.

Is there any way to read the number of rows in the data file, so that I can generalize this code for any data file without knowing the value of N in advance.

NOTE: The number of columns is not changing between different data files.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
RD017
  • 117
  • 5

2 Answers2

0

You have to count the lines yourself (like this for example), and then rewind the file pointer to the start of the file, to actually parse it, now that you found N.

To reset the pointer to the start of the file, do this:

fseek(fptr, 0, SEEK_SET);

Another way is to find out the size of your data and do some calculations, like this:

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

Relevant code can be found here.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
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;  
}  
Yogendra Kumar
  • 113
  • 1
  • 8