Skip to content

Commit

Permalink
Merge pull request #77 from beutlich/close-file-handle
Browse files Browse the repository at this point in the history
Close file handle on exit
  • Loading branch information
JayHuLBL authored Mar 27, 2024
2 parents 8190f02 + 97ce35b commit db95e41
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/readCSV.c
Original file line number Diff line number Diff line change
Expand Up @@ -54,36 +54,39 @@ struct data readCSV(const char * filename, int skipLines) {

FILE *fp;

if (file_exist(filename))
if (!file_exist(filename))
{
fp = fopen(filename, "r");
if (!(fp)) {
fprintf(stderr, "Cannot open file: %s\n", filename);
exit(1);
}
} else {
fprintf(stderr, "No such file: %s\n", filename);
exit(1);
}

fp = fopen(filename, "r");
if (!(fp)) {
fprintf(stderr, "Cannot open file: %s\n", filename);
exit(1);
}

time = malloc(sizeof(double) * arraySize);
if (time == NULL){
fputs("Error: Failed to allocate memory for time.\n", stderr);
fclose(fp);
exit(1);
}
value = malloc(sizeof(double) * arraySize);
if (value == NULL){
fputs("Error: Failed to allocate memory for value.\n", stderr);
exit(1);
fputs("Error: Failed to allocate memory for value.\n", stderr);
fclose(fp);
exit(1);
}

memset(time,0,sizeof(double)*arraySize);
memset(value,0,sizeof(double)*arraySize);

for (i=0; i<skipLines; i++) {
if (fgets(buf, 100, fp) == NULL) { // skip the first "skipLines" lines
fputs("Error: Failed to skip lines with fgets.\n", stderr);
exit(1);
fputs("Error: Failed to skip lines with fgets.\n", stderr);
fclose(fp);
exit(1);
}
}

Expand All @@ -95,6 +98,7 @@ struct data readCSV(const char * filename, int skipLines) {
double *value_tmp = realloc(value, sizeof(double)*(arraySize+1));
if (time_tmp == NULL || value_tmp == NULL) {
fputs("Fatal error -- out of memory!\n", stderr);
fclose(fp);
exit(1);
}
time = time_tmp;
Expand Down

0 comments on commit db95e41

Please sign in to comment.