Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function in C that reads in a single line CSV (comma separated values) t

ID: 2989482 • Letter: W

Question

Write a function in C that reads in a single line CSV (comma separated values) text file. The file is
expected to be a plaintext *.txt file with single digit integer values separated by commas. You
should abide by the following:
? The return value should be -1 if the EOF was reached before the array was filled, -2 if the
EOF was not reached before the array was filled, -3 if opening the file failed, or 0 otherwise.
? values should point to a pre-allocated array with a length of numValues. At the
completion of this function, values should contain the values from the CSV file.
? You can assume:
o There are no empty values in the CSV
o Each value is only a single character (i.e. digit)
o Conversion from the read character to an integer value can be done with the
following function:int char_to_int(char c) {
return c - '0';
}
Use the following function signature for your solution:
int read_basic_csv(char* fileLocation, int numValues, int* values);

Explanation / Answer

#include <stdio.h>

#include <stdlib.h>

#define FIRST_LINE   500

#define LAST_LINE   1000

int main() {

  char buf[1024];

  int line_count = 0;

  FILE *file = fopen("xxx", "r");

  if (!file) {

    fprintf(stderr, "Can't open file. ");

    exit(EXIT_FAILURE);

  }

  while (fgets(buf, sizeof buf, file) != NULL)

    if (++line_count >= FIRST_LINE - 1)

      break;

  while (fgets(buf, sizeof buf, file) != NULL) {

    double value;

    // read value in third column (asterisk means ignore value)

    if (sscanf(buf, "%*lf,%*lf,%lf", &value) != 1) {

      fprintf(stderr, "sscanf failed. ");

      exit(EXIT_FAILURE);

    }

    printf("%f ", value);

    if (++line_count >= 1000)

      break;

  }

  fclose(file);

  return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote