Deutsch   English   Français   Italiano  
<666ded36$0$958$882e4bbb@reader.netnews.com>

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

Path: ...!news-out.netnews.com!postmaster.netnews.com!us14.netnews.com!not-for-mail
X-Trace: DXC=`X:JTF1eEnP_4YChK]9ALRHWonT5<]0T]Q;nb^V>PUfV=AnO\FUBY[PnF54O@^\1?T_og>=_9<RdYZXMZ9Rc<mgUnk9`jfQW@>]dDioXmM8L1QOXeKkS2`?jY
X-Complaints-To: support@blocknews.net
Date: Sat, 15 Jun 2024 15:36:22 -0400
MIME-Version: 1.0
User-Agent: Betterbird (Windows)
Newsgroups: comp.lang.c
Content-Language: en-US
From: DFS <nospam@dfs.com>
Subject: Whaddaya think?
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Lines: 56
Message-ID: <666ded36$0$958$882e4bbb@reader.netnews.com>
NNTP-Posting-Host: 127.0.0.1
X-Trace: 1718480182 reader.netnews.com 958 127.0.0.1:55501
Bytes: 2022

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);
				
}
----------------------------------------------------------