C fwrite() function
C library function - fwrite()
The fwrite() function is used to write up to count items, each of size bytes in length, from buffer to the output stream.
Syntax:
size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
fwrite() Parameters:
Name | Description | Required /Optional |
---|---|---|
buffer | A pointer to the data (to write out) or empty buffer (to read into). | Required |
size | The size (number of bytes) of each element of data. | Required |
count | The number of elements. | Required |
stream | The opened (via fopen) stream. | Required |
Return value from fwrite()
- Returns the number of full items successfully written, which can be fewer than count if an error occurs.
- When using fwrite() for record output, set size to 1 and count to the length of the record to obtain the number of bytes written. You can only write one record at a time when using record I/O.
Example: fwrite() function
Following example write and read a specified string:
#include<stdio.h>
int main () {
FILE *fp;
char str[] = "C programming tutorial.";
fp = fopen( "test.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
fp = fopen("test.txt","r");
int c;
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Output:
C programming tutorial.
Errors: The value of errno can be set to:
Value | Meaning |
---|---|
ECONVERT | A pointer to the data (to write out) or empty buffer (to read into). |
ENOTWRITE | The file is not open for write operations. |
EPAD | Padding occurred on a write operation. |
EPUTANDGET | An illegal write operation occurred after a read operation. |
ESTDERR | stderr cannot be opened. |
ESTDIN | stdin cannot be opened. |
ESTDOUT | stdout cannot be opened. |
ETRUNC | Truncation occurred on I/O operation. |
EIOERROR | A non-recoverable I/O error occurred. |
EIORECERR | A recoverable I/O error occurred. |
C Programming Code Editor:
Previous C Programming: C ftell()
Next C Programming: C remove()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming/stdio/c_library_method_fwrite.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics