Path: ...!news.mixmin.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: Sun, 16 Jun 2024 17:17:52 +0100 Organization: A noiseless patient Spider Lines: 60 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: 7bit Injection-Date: Sun, 16 Jun 2024 18:17:53 +0200 (CEST) Injection-Info: dont-email.me; posting-host="89fd4fc902c96a94ecd3a3858c2eb313"; logging-data="148243"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/Kl/zzIJQpeM5iw/+O5kV23zNiGcCC+5w=" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:o0ly6h6goII3CJWenZdaLC6qGE0= In-Reply-To: Content-Language: en-GB Bytes: 3222 On 16/06/2024 16:52, Lew Pitcher wrote: > On Sat, 15 Jun 2024 15:36:22 -0400, 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? > > Others have (and will continue to) address this question. > >> Any 'better' way? > > Not so much "better", as "other". > > ISTM that you waste an opportunity (and expose a common 'blind-spot') > in your first loop: > > Here, >> while(fscanf(datafile, "%d", &j) != EOF){ >> N++; >> } > you discard a lot of work (done for you by fscanf() to determine the > value of each input number) just to be able to count the number of > numbers in your input. What if there were a way to put this (to you) > byproduct of fscanf() to use, and avoid using fscanf() entirely in > the second pass? > > You /could/ create a temporary, binary, file, and write the fscanf()'ed > values to it as part of the first loop. Once the first loop completes, > you rewind this temporary file, and load your integer array by reading > the (now converted to native integer format) values from that file. > > Still two passes, but using fscanf() in only one of those passes. > > (BTW, the 'blind-spot' I mentioned is that we often forget that > we /can/ use temporary files to store intermediary results. Sometimes > we can manipulate a temporary file easier than we can manipulate > malloc()ed (or other) storage. ) > Exactly. People complain that it is a hassle to realloc() a buffer. So just use a temporary file. -- Check out my hobby project. http://malcolmmclean.github.io/babyxrc