Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The definition does not state that the fwrite() function will stop copying characters into the file if a null character is encountered. Therefore, when writing a null-terminated byte string to a file using the fwrite() function, always use the size length of the buffer string plus 1 (to account for the null character) as the nitems parameter.

...

Code Block
bgColor#ffcccc
#include <stdio.h>
char *buffer = NULL;
longsize_t size1, size2;
FILE *filedes;

/*
 * Assume size1 and size2 are appropriately initialized
 */

filedes = fopen("out.txt", "w+");
if (filedes <== 0NULL) {
  /* Handle error */
}

buffer = (char *)calloc(1, size1);
if (buffer == NULL) {
  /* Handle error */
}

fwrite(buffer, sizeof(char), size2, filedes);

free(buffer);
buffer = NULL;
fclose(filedes);

...

Code Block
bgColor#ccccff
char *buffer = NULL;
longsize_t size1, size2;
FILE *filedes;

/*
 * Assume size1 andis size2 are appropriately initialized
 */

filedes = fopen("out.txt", "w+");
if (filedes <== 0NULL){
  /* Handle error */
}

buffer = (char *)calloc(1, size1);
if (buffer == NULL) {
  /* Handle error */
}

/*
 * Accept characters in to the buffer
 * Check for buffer overflow
 */

size2 = strlen(buffer) + 1;

fwrite(buffer, sizeof(char), size2, filedes);

free(buffer);
buffer = NULL;
fclose(filedes);

...