Fixed easycsv_init for write mode

* easycsv fp member is now char buffer array
* csv_exist now has correct bool value
* easycsv_init now returns NULL if malloc fails or csv file is empty in read mode
* easycsv_free now properly destroys csv

Signed-off-by: Pradana AUMARS <paumars@courrier.dev>
This commit is contained in:
Pradana AUMARS 2021-07-17 15:11:57 +02:00
parent 4b3c7bbb97
commit d6f0b0260e
2 changed files with 30 additions and 43 deletions

View File

@ -61,8 +61,8 @@ typedef struct _easycsv easycsv;
struct _easycsv {
FILE *file; ///< original CSV file
FILE *temp; ///< temporary CSV file for writing
char *fp;
char *tmpfp;
char fp[BUFSIZ];
// char *tmpfp;
unsigned int rows;
unsigned int cols;
// EASYCSV_ERRORMSG error;

View File

@ -11,22 +11,40 @@ easycsv_init(const char *fp,
int csv_exist = -1;
csv = malloc(sizeof(easycsv));
if (csv == NULL) {
easycsv_error(EASYCSV_MEMALLOC, NULL);
return NULL;
}
memset(csv, 0, sizeof(easycsv));
csv->mode = mode;
csv->file = NULL;
csv->temp = NULL;
csv->fp = NULL;
csv->tmpfp = NULL;
strcpy(csv->fp, fp);
csv->rows = 0;
csv->cols = 0;
csv_exist = !access(csv->fp, F_OK);
/* Open file according to mode */
switch (csv->mode) {
case EASYCSV_R:
csv->file = fopen(fp, "r");
if (csv_exist) {
csv->file = fopen(csv->fp, "r");
}
else {
easycsv_error(EASYCSV_EMPTYCSV, NULL);
easycsv_free(csv);
return NULL;
}
break;
case EASYCSV_W:
csv->file = fopen(fp, "w");
if (csv_exist) {
csv->file = fopen(csv->fp, "r+");
}
else {
csv->file = fopen(csv->fp, "w");
}
break;
default:
easycsv_error(EASYCSV_UNKNOWNIOMODE, NULL);
@ -40,15 +58,6 @@ easycsv_init(const char *fp,
return NULL;
}
csv_exist = access(csv->fp, F_OK);
size_t stfp = strlen(fp);
/* Allocate memory for char* */
csv->fp = malloc(stfp + 1); // + 1 for null
strcpy(csv->fp, fp);
/* Calculate rows and cols if file exists */
if (csv_exist) {
csv->rows = easycsv_rows(csv);
@ -56,33 +65,7 @@ easycsv_init(const char *fp,
}
if (mode == EASYCSV_W) {
do {
/* Write to temporary file */
unsigned int i = 1;
char buffer[21] = "/tmp/easycsv-"; // 13 char, 3 for digits, 4 for .csv, 1 for NULL
if (i < 100)
strncat(buffer, "0", 1);
if (i < 10)
strncat(buffer, "0", 1);
sprintf(buffer + strlen(buffer), "%i", i);
strcat(buffer, ".csv");
if (access(buffer, F_OK) < 0) {
i++;
}
else {
csv->tmpfp = malloc(21);
strncpy(csv->tmpfp, buffer, 21);
break;
}
} while (1);
csv->temp = fopen(csv->tmpfp, "w");
csv->temp = tmpfile();
if (csv->temp == NULL) {
easycsv_error(EASYCSV_OPENFAIL, NULL);
easycsv_free(csv);
@ -96,7 +79,11 @@ easycsv_init(const char *fp,
void
easycsv_free(easycsv *csv)
{
if (csv == NULL) free(csv);
if (csv != NULL) {
if (csv->file != NULL) fclose(csv->file);
if (csv->temp != NULL) fclose(csv->temp);
free(csv);
}
}
/*** Acces, find ***/