名稱空間
變體
操作

std::fwrite

來自 cppreference.com
< cpp‎ | io‎ | c
 
 
 
 
定義於標頭檔案 <cstdio>
std::size_t fwrite( const void* buffer, std::size_t size, std::size_t count, std::FILE* stream );

將給定陣列 buffer 中至多 count 個二進位制物件寫入輸出流 stream。寫入物件的方式是:將每個物件重解釋為 unsigned char 陣列,並對每個物件呼叫 std::fputc size 次,以按順序將這些 unsigned char 寫入 stream。流的檔案位置指示器將前進寫入的字元數。

如果物件不是 TriviallyCopyable,則行為未定義。

如果發生錯誤,則流的檔案位置指示器的最終值是不確定的。

目錄

[編輯] 引數

buffer - 指向要寫入陣列中第一個物件的指標
size - 每個物件的大小
count - 要寫入的物件數量
stream - 要寫入的輸出檔案流

[編輯] 返回值

成功寫入的物件數量,如果發生錯誤,此數量可能小於 count

如果 sizecount 為零,fwrite 返回零並且不執行其他操作。

[編輯] 示例

#include <array>
#include <cstdio>
#include <vector>
 
int main ()
{
    // write buffer to file
    if (std::FILE* f1 = std::fopen("file.bin", "wb"))
    {
        std::array<int, 3> v = {42, -1, 7}; // underlying storage of std::array is an array
        std::fwrite(v.data(), sizeof v[0], v.size(), f1);
        std::fclose(f1);
    }
 
    // read the same data and print it to the standard output
    if (std::FILE* f2 = std::fopen("file.bin", "rb"))
    {
        std::vector<int> rbuf(10); // underlying storage of std::vector is also an array
        std::size_t sz = std::fread(rbuf.data(), sizeof rbuf[0], rbuf.size(), f2);
        std::fclose(f2);
        for (std::size_t n = 0; n < sz; ++n)
            std::printf("%d\n", rbuf[n]);
    }
}

輸出

42
-1
7

[編輯] 參閱

將格式化輸出列印到 stdout、檔案流或緩衝區
(函式) [編輯]
將字元字串寫入檔案流
(函式) [編輯]
從檔案讀取
(函式) [編輯]
C 文件 用於 fwrite