Search code examples
cfwritestrcat

fwrite and strcat truncating string and writing nonsense values


When the function shown below is called it write certain parts of the string to a text file. it will sometimes remove characters, so lightning strike number will come out as "ghtning strik number". It has never properly displayed the strike number as a character, it always comes out at "lightning strike number:". I think the problem may be with strcat, but I can't figure out exactly why, any help would be appreciated.

void recordLightningStrike( int strikeNumber, char fileName[], FILE *filePointer )
{
   time_t systemTime;
   struct tm *UTCTime;

   char numberOfStrikes[6];
   char strikeTime[24];
   char stringOne[25];
   char stringTwo[55];
   //char finalString[200];

   itoa( strikeNumber, numberOfStrikes, 10 );
   time( &systemTime );
   UTCTime = localtime( &systemTime );
   strcpy( strikeTime, asctime( UTCTime ) );
   strcpy( stringOne, "Lightning Strike Number: " );
   strcpy( stringTwo, "Lightning Strike Occurred at: " );
   strcat( stringOne, numberOfStrikes );
   strcat( stringTwo, strikeTime );
   //strcpy( finalString, stringOne );
   //strcat( finalString, stringTwo );
   printf( " %s %c ", stringOne, '\n' );
   FILE *openPointer = fopen( fileName, "a" );
   if( openPointer!=NULL )
   {
      fwrite( stringOne, sizeof(char), sizeof(stringOne), openPointer );
      fwrite( stringTwo, sizeof(char), sizeof(stringTwo), openPointer );
   }
   fclose( openPointer );  
}

Solution

  • Declare both buffers (stringOne and stringTwo) bigger. And don't use sizeof() but strlen. Also, for the sake of performance, write each buffer at once, by swapping the arguments size and count (actually, computing the buffer size and writing 1 buffer):

    .
    .
    .
    char stringOne[50]; // guess; you could compute it more tightly
    char stringTwo[60]; // guess; you could compute it more tightly
    .
    .
    .
    fwrite( stringOne, sizeof(char) * strlen(stringOne), 1, openPointer );
    fwrite( stringTwo, sizeof(char) * strlen(stringTwo), 1, openPointer );
    .
    .
    .
    

    The above adjustments will probably correct your program. But you could make it easier to read, using snprintf() to print to the buffer or, even better, fprintf() to print directly to the FILE*:

    fprintf( openPointer, "Lightning Strike Number: %d\n", strikeNumber );
    fprintf( openPointer, "Lightning Strike Occurred at: %s\n", asctime( UTCTime ) );