fread函數的應用,fread函數應用

來源:互聯網
上載者:User

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位元組讀取高度
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.