现在的位置: 首页 > 综合 > 正文

fread函数的应用

2018年04月24日 ⁄ 综合 ⁄ 共 1148字 ⁄ 字号 评论关闭

头文件:<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不相同,则可能文件结尾或发生错误.

ferrorfeof获取错误信息或检测是否到达文件结尾.

例子

 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;
}


抱歉!评论已关闭.