當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C語言 fwrite()用法及代碼示例


C 中的 fwrite() 函數

原型:

    size_t fwrite(void *buffer, size_t length, size_t count, FILE *filename);

參數:

    void *buffer, size_t length, size_t count, FILE *filename

返回類型:size_t

函數的使用:

函數 fwrite() 的原型為:

    size_t fwrite(void *buffer, size_t length, size_t count, FILE *filename);

在文件處理中,我們通過 fwrite() 函數將 count 個大小為 length 的對象從名為 buffer 的數組寫入輸入流文件名。它返回將寫入文件的對象數。如果將寫入的對象數量較少或遇到 EOF,則會引發錯誤。

C 中的 fwrite() 示例

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE* f;
    //initialize the arr1 with values
    int arr1[5] = { 1, 2, 3, 4, 5 };
    int arr2[5];
    int i = 0;

    //open the file for write operation
    if ((f = fopen("includehelp.txt", "w")) == NULL) {
        //if the file does not exist print the string
        printf("Cannot open the file...");
        exit(1);
    }
    //write the values on the file
    if ((fwrite(arr1, sizeof(int), 5, f)) != 5) {
        printf("File write error....\n");
    }
    //close the file
    fclose(f);

    //open the file for read operation
    if ((f = fopen("includehelp.txt", "r")) == NULL) {
        //if the file does not exist print the string
        printf("Cannot open the file...");
        exit(1);
    }
    //read the values from the file and store it into the array
    if ((fread(arr2, sizeof(int), 5, f)) != 5) {
        printf("File write error....\n");
    }
    fclose(f);
    for (i = 0; i < 5; i++) {
        printf("%d\n", arr2[i]);
    }

    return 0;
}

輸出

fwrite example in c




相關用法


注:本文由純淨天空篩選整理自Souvik Saha大神的英文原創作品 fwrite() function in C language with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。