arrays - Reading a stream of values from text file in C -


i have text file may contain 1 or 400 numbers. each number separated comma , semicolon used indicate end of numbers stream. @ moment reading text file line line using fgets. reason using fixed array of 1024 elements (the maximum characters per line text file). not ideal way how implement since if 1 number inputted in text file, array of 1024 elements pointless. there way use fgets malloc function (or other method) increase memory efficiency?

if looking using in production code request follow suggestions put in comments section.

but if requirement more learning or school, here complex approach.

pseudo code

1. find size of file in bytes, can use "stat" this. 2. since file format known, file size, calculate number of items. 3. use number of items malloc. 

voila! :p

how find file size

you can use stat shown below:

#include <sys/stat.h> #include <stdio.h>  int main(void) {     struct stat st;      if (stat("file", &st) == 0) {         printf("filesize: %d  no. of items: %d\n", (st.st_size), (st.st_size/2));         return st.st_size;     }      printf("failed!\n");     return 0; } 

this file when run return file size:

$> cat file 1; $> ./a.out filesize: 3  no. of items: 1  $> cat file 1,2,3; $> ./a.out filesize: 7  no. of items: 3 

disclaimer: approach minimize pre-allocated memory optimal approach? no ways in heaven! :)