The C standard defines the fwrite() function as follows
size_t fwrite(const void *restrict ptr
| Wiki Markup |
|---|
The POSIX standard defines the {{write()}} interface as follows \[1\]. |
ssize_t write (int filedes, const void *buffer, size_t size, size_t nitems, FILE *restrict stream);
The write function writes up to size bytes from buffer to the file with descriptor filedes. The data in buffer is not necessarily a character string and a null character is output like any other character
fwrite()function shall write, from the array pointed to byptr, up tonitemselements whose size is specified bysize, to the stream pointed to bystream. For each object,sizecalls shall be made to thefputc()function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file-position indicator for the stream (if defined) shall be advanced by the number of bytes successfully written. If an error occurs, the resulting value of the file-position indicator for the stream is unspecified.
The definition does not state that the writefwrite() function will stop copying characters into the file if a null character is encountered. Therefore, when writing a C string in to a file using the writefwrite() function, always use the size of the buffer string plus 1 (to account for the null character) as the size nitems parameter.
Noncompliant Code Example
...
| Code Block | ||
|---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> int main(){ char *buffer = NULL; long size1, size2; intFILE *filedes; /* ... * Assume size1 and size2 are appropriately initialized * ... */ filedes = openfopen("out.txt", O_CREAT | O_WRONLY"w+"); if (filedes < 0) return 0; buffer = (char *)calloc(1, size1); if (!buffer) return 0; writefwrite(filedesbuffer, buffersizeof(char), size2, filedes); free(buffer); buffer = NULL; closefclose(filedes); return 0; } |
Compliant Code Example
...
| Code Block | ||
|---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> int main(){ char *buffer = NULL; long size1, size2; intFILE *filedes; /* ... * Assume size1 and size2 are appropriately initialized * ... */ filedes = openfopen("out.txt", O_CREAT | O_WRONLY"w+"); if (filedes < 0) return 0; buffer = (char *)calloc(1, size1); if (!buffer) return 0; /* ... * Accept characters in to the buffer * Check for buffer overflow * ... */ size2 = strlen(buffer) + 1; writefwrite(filedesbuffer, buffersizeof(char), size2, filedes); free(buffer); buffer = NULL; closefclose(filedes); return 0; } |
References
| Wiki Markup |
|---|
\[1\] [http://www.gnuopengroup.org/softwareonlinepubs/libc009695399/manualfunctions/html_node/I_002fO-Primitives.html#I_002fO-Primitivesfwrite.html] |