Deutsch English Français Italiano |
<20240616015649.000051a0@yahoo.com> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Michael S <already5chosen@yahoo.com> Newsgroups: comp.lang.c Subject: Re: Whaddaya think? Date: Sun, 16 Jun 2024 01:56:49 +0300 Organization: A noiseless patient Spider Lines: 66 Message-ID: <20240616015649.000051a0@yahoo.com> References: <666ded36$0$958$882e4bbb@reader.netnews.com> MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Injection-Date: Sun, 16 Jun 2024 00:56:57 +0200 (CEST) Injection-Info: dont-email.me; posting-host="80e0c2bced6a7a3e7e096b2e292da6ed"; logging-data="3776572"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19W9XOVNIPU8MqONLeEAQWXIjsavN9eJkw=" Cancel-Lock: sha1:bTuo1WC9T7xxBbYQ0EBuxuj6Wio= X-Newsreader: Claws Mail 4.1.1 (GTK 3.24.34; x86_64-w64-mingw32) Bytes: 2457 On Sat, 15 Jun 2024 15:36:22 -0400 DFS <nospam@dfs.com> 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 <stdio.h> > #include <stdlib.h> > > 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<N;i++) { > printf("%d. %d\n", i+1, nums[i]); > } > printf("\n"); > free(nums); > return(0); > > } > ---------------------------------------------------------- > > If you want to preserve you sanity, never use fscanf().