C++ 程式中的 fread() 函式


給定的任務是展示 fread() 在 C++ 中的工作原理。在本文中,我們還將瞭解傳遞給 fread() 的不同引數以及此函式返回的內容。

fread() 是 C++ 的一個內建函式,用於從流中讀取資料塊。此函式計算從流中讀取的每個大小為“size”位元組的物件的數量,並將它們儲存在緩衝區記憶體中,然後將位置指標向前移動讀取的總位元組數。如果讀取成功,讀取的位元組數將為 size * count。

語法

fread(void *buffer, size_t size, size_t count, FILE *file_stream);

引數

此函式需要所有 4 個引數。讓我們瞭解這些引數。

  • buffer - 這是一個指向緩衝區記憶體塊的指標,從流中讀取的位元組將儲存在此處。

  • size - 它定義了要讀取的每個元素的大小(以位元組為單位)。(size_t 是無符號整數)。

  • count - 要讀取的元素數量。

  • file_stream - 我們要從中讀取位元組的檔案流的指標。

返回值

返回成功讀取的元素數量。

如果發生任何讀取錯誤或到達檔案末尾,返回的元素數量將與 count 變數不同。

示例

#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int main() {
   FILE* file_stream;
   char buf[100];
   file_stream = fopen("tp.txt", "r");
   while (!feof(file_stream)) //will read the file {
      // will read the contents of the file.
      fread(buf, sizeof(buf), 1, file_stream);
      cout << buf;
   }
   return 0;
}

假設 tp.txt 檔案包含以下內容

tutorialspoint

Contribution

anything here

輸出

如果我們執行上述程式碼,它將生成以下輸出:

tutorialspoint
Contribution
anything here

讓我們舉個例子,檢查當 count 為零且 size 為零時的輸出。

示例

即時演示

#include <iostream>
#include <cstdio>
using namespace std; int main() {
   FILE *fp;
   char buffer[100];
   int retVal;
   fp = fopen("tpempty.txt","rb");
   retVal = fread(buffer,sizeof(buffer),0,fp);
   cout << "The count = 0, then return value = " << retVal << endl;
   retVal = fread(buffer,0,1,fp);
   cout << "The size = 0, then value = " << retVal << endl;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

The count = 0, then return value = 0
The size = 0, then value = 0

更新於: 2020年2月28日

820 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.