Author Topic: Solution to Exercise 5, Day2 - Reading from Large Binary Files  (Read 19 times)


  • Newbie
  • *
  • Posts: 6
    • View Profile
Solution to Exercise 5, Day2 - Reading from Large Binary Files
« on: January 10, 2021, 07:58:15 PM »
I couldn't find solution to exercise5 day2 for reading large binary file in official NHERI github folder:

Will the correct solution of file3.c be provided so that I can verify my answer.

Also the file3.c gives no error when I compile on gcc 10.2.0, msys2. But it gives error on icc.

Here is my solution that works on icc without error, is it correct:

Code: [Select]
// program to read values from a file, each file a csv list of int and two double
// written: fmk
// exercise solved by: fr

#include <stdio.h>
#include <stdlib.h>

int getcountlines(char *filename);

int main(int argc, char **argv) {

  if (argc != 2) {
    fprintf(stdout, "ERROR correct usage appName inputFile\n");
    return -1;

  //count total number of lines from very beginning just in case
  //if lines exceeds maxVectorSize (100)

  int countlines = 0; //used to count lines

  // count lines
  countlines = getcountlines(argv[1]);
  if (countlines == -1){
    printf("the text file is empty\n aborting program ...\n");
    return -1;
  printf("total number of lines are: %i\n\n",countlines);
  FILE *filePtr = fopen(argv[1],"r");

  int i = 0;
  float float1, float2;
  int maxVectorSize = 100;
  double *vector1 = (double *)malloc(maxVectorSize*sizeof(double));
  double *vector2 = (double *)malloc(maxVectorSize*sizeof(double));

  int vectorSize = 0;

  while (fscanf(filePtr,"%d, %f, %f\n", &i, &float1, &float2) != EOF) {
    vector1[vectorSize] = float1;
    vector2[vectorSize] = float2;
    printf("%d, %f, %f\n",i, vector2[i], vector1[i]);
    if (vectorSize == maxVectorSize) {
      maxVectorSize = countlines;
      vector1 = (double *) realloc(vector1,maxVectorSize*sizeof(double)); // allocate again
      vector2 = (double *) realloc(vector2,maxVectorSize*sizeof(double)); // allocate again

//function to countlines
int getcountlines(char *filename)
  // count the number of lines in the file called filename                                   
  FILE *fp = fopen(filename,"r");
  int ch=0;
  int lines=0;

  if (fp == NULL){
   return -1;

 while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp,"%*c")))
 return lines;