Path: ...!news.misty.com!weretis.net!feeder9.news.weretis.net!feeder8.news.weretis.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Malcolm McLean Newsgroups: comp.lang.c Subject: Re: Whaddaya think? Date: Sat, 15 Jun 2024 22:33:00 +0100 Organization: A noiseless patient Spider Lines: 64 Message-ID: References: <666ded36$0$958$882e4bbb@reader.netnews.com> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Sat, 15 Jun 2024 23:33:00 +0200 (CEST) Injection-Info: dont-email.me; posting-host="d215d4324750730ebb6b30950f8c5d51"; logging-data="3827728"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19W9L4OmsS1c3Q99bN9tH3c20xhejqLUD8=" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:QzQdat8w1MqWLCJkxoR5XIJShGA= In-Reply-To: <666ded36$0$958$882e4bbb@reader.netnews.com> Content-Language: en-GB Bytes: 2941 On 15/06/2024 20:36, DFS wrote: > I want to read numbers in from a file, say: > > 47 185 99 74 202 118 78 203 264 207 19 17 34 167 148 54 297 271 118 245 > 294 188 140 134 251 188 236 160 48 189 228 94 74 27 168 275 144 245 178 > 108 152 197 125 185 63 272 239 60 242 56 4 235 244 144 69 195 32 4 54 79 > 193 282 173 267 8 40 241 152 285 119 259 136 15 83 21 78 55 259 137 297 > 15 141 232 259 285 300 153 16 4 207 95 197 188 267 164 195 7 104 47 291 > > > This code: > 1 opens the file > 2 fscanf thru the file to count the number of data points > 3 allocate memory > 4 rewind and fscanf again to add the data to the int array > > > Any issues with this method? > > Any 'better' way? > > Thanks > > > ---------------------------------------------------------- > #include > #include > > int main(int argc, char *argv[]) { > >     int N=0, i=0, j=0; >     int *nums; > >     FILE* datafile = fopen(argv[1], "r"); >     while(fscanf(datafile, "%d", &j) != EOF){ >         N++; >     } > >     nums = calloc(N, sizeof(int)); >     rewind(datafile); >     while(fscanf(datafile, "%d", &j) != EOF){ >         nums[i++] = j; >     } >     fclose (datafile); >     printf("\n"); > >     for(i=0;i         printf("%d. %d\n", i+1, nums[i]); >     } >     printf("\n"); >     free(nums); >     return(0); > > } > ---------------------------------------------------------- > > Some files can't be rewound. Whilst C doesn't have dynamic arrays, languages tha do suooort then usually build them on top of the C-linked realloc() function. It's redious, but not hard to do. -- Check out my hobby project. http://malcolmmclean.github.io/babyxrc