d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > C Problem > Reading In Reversed Numbers
Add Reply New Topic New Poll
Member
Posts: 2,081
Joined: Jan 13 2007
Gold: 515.76
Sep 25 2012 08:22pm
from a .data file with integer values
read in first value from this file
then reserve space in the heap to hold an array of n integers. using malloc
then fill the array with n integers using the next n values within the file
print out the values in the reverse order they are written

what i have so far

#include <stdio.h>

int main( int argc, char *argv[] ) {

int n ;
int *A ;
File *fin ;
fin = fopen( "p9.data", "r" ) ;
fscanf( fin, "%", &n ) ;

A = ( int * ) malloc( n * sizeof(int) )
for( i = 0; i < n ; i++ ) fscanf( fin, "%d", &A[ i ] )

Some help would be greatly appreciated.
Thanks.
Member
Posts: 16,144
Joined: Mar 27 2008
Gold: 14,618.00
Sep 26 2012 12:15pm
dont forget the semicolon in the line where you malloc the space for A.
include stdlib.h to be able to malloc
close the file pointer of the file you opened
dont forget to free the stuff you malloc'ed
i guess FILE needs to be written in uppercase
at fscanf you need to tell the format with the right syntax (%d instead of %)
for debugging, check if your "n" is the right number, before you code more (printf("%d\n",n); right after fscanf of "n")
Member
Posts: 13,425
Joined: Sep 29 2007
Gold: 0.00
Warn: 20%
Sep 26 2012 07:35pm
how is the .data file formatted?

if there is one integer per line i would use fgets and just realloc the array every iteration of a loop reading the file until EOF.

although using too many reallocs may fragment your memory.
Member
Posts: 2,081
Joined: Jan 13 2007
Gold: 515.76
Sep 26 2012 08:26pm
Quote (AbDuCt @ Sep 27 2012 01:35am)
how is the .data file formatted?

if there is one integer per line i would use fgets and just realloc the array every iteration of a loop reading the file until EOF.

although using too many reallocs may fragment your memory.


I got this program done thank you guys (yes it was one integer per line)
(btw didnt use realloc or fget)
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll