#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int Type;
typedef struct vector {
size_t size;
size_t capacity;
Type *array;
} Vector;
Vector *vec_make(void){
Vector *v = malloc(sizeof(*v));
if(v){
v->size = 0;
v->capacity=16;
v->array = malloc(v->capacity * sizeof(Type));
}
return v;
}
void vec_free(Vector *v){
free(v->array);
free(v);
}
void vec_add(Vector *v, Type value){
v->array[v->size++] = value;
if(v->size == v->capacity){
Type *temp;
temp = realloc(v->array, sizeof(Type)*(v->capacity += 16));
if(!temp){
perror("realloc at vec_add");
vec_free(v);
exit(-1);
}
v->array = temp;
}
}
int main(int argc, char *argv[]){
if(argc != 2){
fprintf(stderr, "Usage : %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *f = fopen(argv[1], "r");
if(f == NULL){
perror("fopen");
exit(EXIT_FAILURE);
}
char line[4096];
while(fgets(line, sizeof line, f)){
static const char *delimiter = "[,] \t\n";
Vector *v = vec_make();
char *number = strtok(line, delimiter);//Format don't check
for(; number; number = strtok(NULL, delimiter)){
vec_add(v, atoi(number));
}
//some operation : print out
int size = v->size;
int *a = v->array;
for(int i = 0; i < size; ++i){
if(i)
putchar(',');
printf("%d", a[i]);
}
putchar('\n');
vec_free(v);
}
fclose(f);
return 0;
}
solved Reading Multiple lines(different lengths) from file in c