Thanks again for everyone's input. I dug around and found the old code from which this originates. Mind you, this works but it doesn't feel right and I'm not sure of one particular part. I stripped the code to keep it small for posting.
First, here is a data file named ttt.dat
05/16/08 22:31 aaaa
05/16/08 22:32 bbb
05/16/08 22:33 asdfasdf
Each line needs to be manipulated so I read each line as one string and then start manipulation. Here is the code:
Code:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define NumberOfNotes 25 /* The number of notes the program will allow */
typedef struct { /* structure of note */
char nBody[20]; /* text of note */
char nExtra[300]; /* area for extra info such as date string */
} NOTEINFO;
NOTEINFO *note[NumberOfNotes] ;
main ()
{
FILE *dataStream ;
int ctr ; /* utility counter */
int finis = 0 ; /* boolen for testing */
char noteContent[300] = "" ; /* string for manipulation of file data */
for( ctr = 0; ctr < NumberOfNotes; ctr++ ) /* loop through number of notes */
{ note[ctr] = (NOTEINFO *)malloc( sizeof( NOTEINFO ) ) ; /* allocate memory */
if( note[ctr] == NULL )
{ printf( "Error allocating." ) ; /* print error */
finis = 1 ;
}
}
dataStream = fopen( "ttt.dat", "r" ) ; /* open file for reading */
if( dataStream == NULL ) /* test opening */
{ printf( "Error opening file." ) ; /* print error message */
finis = 1 ;
}
ctr = 0;
while( !finis )
{
if( fgets( noteContent, 300, dataStream ) == NULL ) /* read the string */
finis = 1 ; /* set boolean for end of read */
else
{ strncpy( note[ctr]->nExtra, noteContent, 14 ) ; /* copy first 14 chars to nExtra */
printf( note[ctr]->nExtra ) ; /* print nExtra */
printf( "\n" ) ;
strncpy( note[ctr]->nBody, ¬eContent[19], strlen( noteContent) - 1 ) ;
printf( note[ctr]->nBody ) ; /* print nBody */
}
ctr++ ;
}
fclose( dataStream );
for( ctr = 0; ctr < NumberOfNotes; ctr++ ) /* loop through all note variables */
free( note[ctr] ) ; /* free the memory */
return( 0 ) ;
}
First I'm confused with the strncpy(). It is used twice: first to grab the date info via:
Code:
strncpy( note[ctr]->nExtra, noteContent, 14 ) ;
And then for the note body:
Code:
strncpy( note[ctr]->nBody, ¬eContent[19], strlen( noteContent) - 1 ) ;
As I understand, the second param to strncpy is a string pointer. Why do I need the "&" in the second strncpy but not the first?
Second, the whole things just looks sloppy. I'm open for suggestions on cleaner code.
Thanks in advance.
Dale L