Hi,
I ve array of structure..
Code:
struct record
{
int key;
char *word;
} Record;
my 1st task is to read the file (ex: struct.txt) which contain such a data....
Code:
24109 vinegar
16554 papacy
12127 integrity
9429 gale
13154 Laramie
21442 squeak
3385 buss
6875 disturbance
16119 Olaf
446 afterimage
14399 Maxwellian
13588 lisle
6109 Deanna
16130 oleomargarine
13828 luck
15314 muscular
6936 DOD
5930 cyclic
20096 sector
20975 snook
7189 drudge
what i want to do is scan the integer and put it in the int key and scan the word, and put it in char *word, after done with one structure then proceed to second structure (second array)...
this is all what i ve done at the moment:
Code:
/* This is the function to open 'fname' in the required mode, if fname cannot be opened, then print error and 'exit-fail' */
FILE *open_file( char *progname, char *fname, const char *mode )
{
FILE *fp;
fp = fopen( fname, mode );
if( fp == NULL )
{
fprintf( stderr, "%s: ERROR: File \"%s\" not opened; Progname execution"
" terminated.\n", progname, fname );
exit( EXIT_FAILURE );
}
return fp;
}
/* This function read word from textfile (input), and then store the word first into 'buffer', then stored it to dynamic memory, then return the wordpointer, otherwise if the end of the reached the return NULL. */
char *get_word( FILE *fp )
{
char *wordptr;
char buffer[WORDSIZE];
if( ( fscanf( fp, "%s", buffer ) ) == 1 )
{
wordptr = create_word_array( strlen( buffer ) );
strcpy( wordptr, buffer );
return wordptr;
}
else
{
return NULL;
}
}
/* This function allocate memory for (len+1) * size of chars, then return the address of that dynamically allocated memory. If memory allocation fail, then 'exit-fail'. */
char *create_word_array( int len )
{
char *ptr;
ptr = ( char* ) malloc( ( len + 1 ) * sizeof( char ) );
if( ptr == NULL )
{
fprintf( stderr, "Memory allocation failed; program terminated.\n" );
exit( EXIT_FAILURE );
}
return ptr;
}
however I dont know how to read the int and then continue read the word, then proceed to next structure...i am thinking of doing it this way, but it's not working *_* (this is not scanning though, i coz i dont know what scanning method I can use)
Code:
void print_record( File *fp )
{
int i;
for ( i = 0 ; i < ASIZE ; i++ )
{
printf( "%d\t%s\n", data[i].key, data[i].word );
}
printf( "\n" );
return;
}
any help will be appreciated...
thanks.
CyC|OpS