C 程式設計/stdio.h/fwrite
外觀
fread 和 fwrite 函式分別提供輸入和輸出的檔案操作。fread 和 fwrite 在 <stdio.h> 中宣告。它通常包裝寫入操作。
fwrite 定義為
int fwrite ( const void * array, size_t size, size_t count, FILE * stream );
fwrite 函式將資料塊寫入流。它將向流中的當前位置寫入 count 個元素的陣列。對於每個元素,它將寫入 size 個位元組。流的位置指示器將根據成功寫入的位元組數進行調整。
該函式將返回成功寫入的元素數量。如果寫入成功完成,則返回值將等於 count。如果發生寫入錯誤,則返回值將小於 count。
以下程式開啟一個名為sample.txt的檔案,將字元陣列寫入檔案,然後關閉它。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file_ptr;
int iCount;
char arr[6] = "hello";
file_ptr = fopen("sample.txt", "wb");
iCount = fwrite(arr, 1, 5, file_ptr);
fclose(file_ptr);
return 0;
}