std::fwrite - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::fwrite

From cppreference.com
< cpp‎ | io‎ | c

Defined in header `<cstdio>` |  |
std::size_t fwrite( const void* buffer, std::size_t size, std::size_t count, std::FILE* stream ); |  |

Writes up to `count` binary objects from the given array `buffer` to the output stream `stream`. The objects are written as if by reinterepreting each object as an array of unsigned char and calling std::fputc `size` times for each object to write those unsigned chars into `stream`, in order. The file position indicator for the stream is advanced by the number of characters written.

If the objects are not `TriviallyCopyable`, the behavior is undefined.

If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.

### [edit] Parameters

buffer | - | pointer to the first object object in the array to be written
size | - | size of each object
count | - | the number of the objects to be written

### [edit] Return value

Number of objects written successfully, which may be less than `count` if an error occurred.

If `size` or `count` is zero, `fwrite` returns zero and performs no other action.

### [edit] Example

Run this code

    #include <cstdio>

    int main ()
    {
        // write buffer to file
        std::FILE *f1;
        char buffer[] = { 'x' , 'y' , 'z' };
        f1 = std::fopen("file.bin", "wb");
        std::fwrite(buffer, sizeof(char), sizeof(buffer), f1);
        std::fclose(f1);

        // read the same data and print it to the standard output
        std::FILE *f2;
        char rbuf[10];
        f2 = std::fopen("file.bin", "rb");
        const char* res = std::fgets(rbuf, sizeof(rbuf), f2);
        std::fclose(f2);

        if (res) { // points to rbuf on read success, NULL on failure
            std::puts(res);
        }
    }

Output:

    xyz

### [edit] See also

printffprintfsprintfsnprintf (C++11) | prints formatted output to stdout, a file stream or a buffer (function) [edit]
fputs | writes a character string to a file stream (function) [edit]
fread | reads from a file (function) [edit]
C documentation for fwrite

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/io/c/fwrite&oldid=67573"