Deutsch   English   Français   Italiano  
<v4n1nf$2fae$1@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!news.mixmin.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Lew Pitcher <lew.pitcher@digitalfreehold.ca>
Newsgroups: comp.lang.c
Subject: Re: Whaddaya think?
Date: Sun, 16 Jun 2024 15:52:16 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 53
Message-ID: <v4n1nf$2fae$1@dont-email.me>
References: <666ded36$0$958$882e4bbb@reader.netnews.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Sun, 16 Jun 2024 17:52:16 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="ff25de1792a6ef76a7a0bc038582b51e";
	logging-data="81230"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX18/DVutRrA5TAYs4vTL3n+wKKexUvWjF0A="
User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508
 git://git.gnome.org/pan2)
Cancel-Lock: sha1:xNR1FuQ2OeCplUfUAsOG4beyhe0=
Bytes: 2898

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. )
-- 
Lew Pitcher
"In Skills We Trust"