Write elements to a file
#include <stdio.h>
size_t fwrite( const void* buf,
size_t size,
size_t num,
FILE* fp );
libc
The fwrite() function writes num elements of size bytes each to the stream specified by fp.
The number of complete elements successfully written; if an error occurs, this will be less than num.
If an error occurs, errno will be set to indicate the type of error.
#include <stdio.h>
#include <stdlib.h>
struct student_data {
int student_id;
unsigned char marks[10];
};
int main( void )
{
FILE *fp;
struct student_data std;
int i;
fp = fopen( "file", "w" );
if( fp != NULL ) {
std.student_id = 1001;
for( i = 0; i < 10; i++ ) {
std.marks[i] = (unsigned char)(85 + i);
}
/* write student record with marks */
i = fwrite( &std, sizeof( struct student_data ), 1, fp );
printf( "Successfully wrote %d records\n", i );
fclose( fp );
if( i == 1 ) {
return EXIT_SUCCESS;
}
}
return EXIT_FAILURE;
}
| Safety: | |
|---|---|
| Cancellation point | Yes |
| Interrupt handler | No |
| Signal handler | No |
| Thread | Yes |