O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code Sample 8.3: Write String to File

long int WriteString( FILE * hFile, char * szString )
{
  long int lNumChars, lItemsWritten;

  // Check the file pointer is valid
  if (hFile == NULL )
  {
    return -1;
  }

  // Count the number of characters in szString
  lNumChars = strlen( szString );

  // Write the two data blocks
  fwrite( &lNumChars, sizeof(lNumChars), 1, hFile);
  lItemsWritten =
     fwrite( szString, sizeof(char), lNumChars, hFile);

  return lItemsWritten;
}

Notice that this example uses the sizeof function to return the size of the variable to be written. The reason for this is that different systems will have different sizes of the basic types (a two-byte character, for example). The caveat is that a file created with the previous function on a one-byte character ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required