fread函數的應用,fread函數應用
標頭檔:<cstdio/stdio.h>
作用:從一個檔案流中讀資料。最多讀取count個元素,每個元素size位元組,如果調用成功返回實際讀取到的元素個數,如果不成功或讀到檔案末尾返回 0。
函數原型:size_t fread ( void *buffer, size_t size, size_t count, FILE *stream)
解析:
buffer:用於接受資料的記憶體位址
size:要讀寫的位元組數,單位是位元組
count:要進行讀寫多少個size位元組的資料項目,每個元素是size位元組.
stream:輸入資料流
返回值:實際讀取的元素個數.如果返回值與count不相同,則可能檔案結尾或發生錯誤.
從ferror和feof擷取錯誤資訊或檢測是否到達檔案結尾.
例子
long long a;
fread(&a,sizeof(long long),1,std);
char b[10];
fread(b,sizeof(char),10,std);
題目應用:
UvaLive 6426 - Count:
連結:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4437
題目中說資料是從二進位流中讀入,而且資料量達到了10000*10000,用scanf,輸入外掛都會逾時,用fread輸入則不會逾時。
代碼:
#include<iostream>#include<cstdio>#include<algorithm>#include<vector>#include<cstring>using namespace std;int m,n;int a[10005][10005];int main(){ int c; fread(&n,sizeof(int),1,stdin); fread(&m,sizeof(int),1,stdin); for(int i=0;i<n;i++) { fread(a[i],sizeof(int),m,stdin); } int l,r; int last=m; while(fread(&l,sizeof(int),1,stdin)) { fread(&r,sizeof(int),1,stdin); int ans=0; for(int i=0;i<n;i++) { if(a[i][0]>r)break; int ll=lower_bound(a[i],a[i]+last,l)-a[i]; int rr=upper_bound(a[i],a[i]+last,r)-a[i]; if(rr<=ll)continue; ans+=rr-ll; } printf("%d\n",ans); } return 0;}
有關fread函數的使用問題
會不會是只對p分配了空間,而對 p->next 沒有分配空間呢?
對於檔案讀取,fseek,fread函數的使用
從檔案開頭18位元組 讀取 寬度 width 長度是2位元組
然後再從寬度 width 後的2位元組讀取高度