Skip to content

Instantly share code, notes, and snippets.

@arnabanimesh
Last active January 10, 2023 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnabanimesh/ce69b0d4499c46e694c9bdd7a94b117b to your computer and use it in GitHub Desktop.
Save arnabanimesh/ce69b0d4499c46e694c9bdd7a94b117b to your computer and use it in GitHub Desktop.
read a file with three tab separated columns. Ignore the first column, the second column is a string, the third column is a number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
typedef struct
{
char *SKU;
long *count;
} Data;
void free_data(Data *data, int nrows);
Data *read_data(const char *filename, int *nrows);
int main(void)
{
int nrows;
int i = 0;
Data *data = read_data("C:\\data.txt", &nrows);
system("cls");
if (data == NULL)
{
return 1;
}
for (i = 0; i < nrows; i++)
{
printf("%s, %ld\n", data[i].SKU, *data[i].count);
}
free_data(data, nrows);
return 0;
}
void free_data(Data *data, int nrows)
{
int i;
for (i = 0; i < nrows; i++)
{
free(data[i].SKU);
free(data[i].count);
}
free(data);
}
Data *read_data(const char *filename, int *nrows)
{
FILE *fp = fopen(filename, "r");
Data *data = NULL;
char line[MAX_LINE_LENGTH];
int n = 0;
int i = 0;
long *count = NULL;
if (fp == NULL)
{
perror("Error opening file");
return NULL;
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL)
{
n++;
}
rewind(fp);
if (n > 0)
{
data = (Data *)malloc(n * sizeof(Data) + 1);
if (data == NULL)
{
perror("Error allocating memory");
fclose(fp);
return NULL;
}
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL)
{
data[i].SKU = (char *)malloc((strlen(line) + 1) * sizeof(char));
count = (long *)malloc(sizeof(long));
if (data[i].SKU == NULL)
{
perror("Error allocating memory");
fclose(fp);
free_data(data, n);
return NULL;
}
if (count == NULL)
{
perror("Error allocating memory");
fclose(fp);
free_data(data, n);
}
sscanf(line, "%*d %s %ld", data[i].SKU, count);
data[i].count = count;
i++;
}
fclose(fp);
*nrows = n;
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment