读取文件c语言fread(c语言 读文件)

本篇文章给大家谈谈读取文件c语言fread,以及c语言 读文件对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

1、c语言fread函数的用法2、程序员的自我修养: fread-C语言是怎样读取文件的3、c语言中fread函数怎么用

c语言fread函数的用法

C语言中:fread是一个函数。从一个文件流中读数据,最多读取count个元素,每个元素size字节,如果调用成功返回实际读取到的元素个数,如果不成功或读到文件末尾返回 0。下面我们来看看c语言fread函数的用法。

fread()函数—- Reads data from a stream.

#includestdio.h

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

从一个文件流中读数据,读取count个元素,每个元素size字节.如果调用成功返回count.如果调用成功则实际读取size*count字节

buffer的大小至少是 size*count 字节.

return:

fread returns the number of full items actually read

实际读取的元素数.如果返回值与count(不是count*size)不相同,则可能文件结尾或发生错误.

从ferror和feof获取错误信息或检测是否到达文件结尾.

DEMO:

[cpp] view plain#include stdio.h

#include process.h

#include string.h

int main()

{

FILE *stream;

char msg[]=”this is a test”;

char buf[20];

if ((stream=fopen(“dummy.fil”,”w+”))==NULL)

{

fprintf(stderr,”cannot open output file.\n”);

return 1;

}

/*write some data to the file*/

fwrite(msg,1,strlen(msg)+1,stream);

/*seek to the beginning of the file*/

fseek(stream,0,SEEK_SET);

/*read the data and display it*/

fread(buf,1,strlen(msg)+1,stream);

printf(“%s\n”,buf);

fclose(stream);

system(“pause”);

return 0;

}

DEMO2

[cpp] view plainint main(void)

{

FILE *stream;

char list[30];

int i,numread,numwritten;

/*open file in text mode:*/

if ((stream=fopen(“fread.out”,”w+t”))!=NULL)

{

for (i=0;i25;i++)

{

list[i]=(char)(‘z’-i);

}

/*write 25 characters to stram*/

numwritten=fwrite(list,sizeof(char),25,stream);

printf(“Wrote %d items\n”,numwritten);

fclose(stream);

}

else

printf(“Problem opening the file\n”);

if ((stream=fopen(“fread.out”,”r+t”))!=NULL)

{

numread=fread(list,sizeof(char),25,stream);

printf(“Number of items read =%d\n”,numread);

printf(“Contents of buffer=%.25s\n”,list);

fclose(stream);

}

else

{

printf(“File could not be opened\n”);

}

system(“pause”);

return 0;

}

读取文件c语言fread(c语言 读文件)

程序员的自我修养: fread-C语言是怎样读取文件的

为了效率的考虑,不至于频繁调用系统函数和访问IO设备,MSVC CRT的fread采用缓冲设计. C语言提供的关于缓冲的函数有:int flush(FILE* stream); int setvbuf(FILE* stream, char* buf, int mode, size_t size); /* 缓冲模式mode有: 1. 无缓冲模式 _IONBF 2. 行缓冲模式 _IOLBF 每收到一个换行符(/n或/r/n), 就将缓冲flush掉 3. 全缓冲模式 _IOFBF 仅当缓冲满时才进行flush */ void setbuf(FILE* stream, char* buf); 等价于 (void)setvbuf(stream, buf, _IOBBF, BUFSIZ); fread的调用过程大概是:fread – fread_s(增加缓冲溢出保护, 加锁) – _fread_nolock_s(循环读取,缓冲) – _read(换行符转换) – ReadFile(读取文件) 加注释的FILE结构如下:struct _iobuf { char *_ptr; int _cnt; //剩余未读的字节数 char *_base; //文件的缓冲基址 int _flag; //打开文件的属性 int _file; //打开文件的编号 int _charbuf; int _bufsiz; //文件的缓冲的总的大小 char *_tmpfname; }; typedef struct _iobuf FILE; 核心函数_fread_nolock_s(循环读取,缓冲)如下:size_t __cdecl _fread_nolock_s( void *buffer, size_t bufferSize, size_t elementSize, size_t num, FILE *stream ) { char *data; /* point inside the destination buffer to where we need to copy the read chars */当前放进字节的尾部 size_t dataSize; /* space left in the destionation buffer (in bytes) //buffer中剩余字节数*/ size_t total; /* total bytes to read //总共要读的字节数*/ size_t count; /* num bytes left to read //剩下要读的字节数*/ unsigned streambufsize; /* size of stream buffer */ unsigned nbytes; /* how much to read now */ unsigned nread; /* how much we did read */ int c; /* a temp char */ /* initialize local vars */ data = buffer; dataSize = bufferSize; if (elementSize == 0 || num == 0) { return 0; } /* validation */ _VALIDATE_RETURN((buffer != NULL), EINVAL, 0); if (stream == NULL || num (SIZE_MAX / elementSize)) { if (bufferSize != SIZE_MAX) { memset(buffer, _BUFFER_FILL_PATTERN, bufferSize); } _VALIDATE_RETURN((stream != NULL), EINVAL, 0); _VALIDATE_RETURN(num = (SIZE_MAX / elementSize), EINVAL, 0); } count = total = elementSize * num; if (anybuf(stream)) { /* already has buffer, use its size */ streambufsize = stream-_bufsiz; } else { /* assume will get _INTERNAL_BUFSIZ buffer */ streambufsize = _INTERNAL_BUFSIZ; } /* here is the main loop — we go through here until we’re done */ while (count != 0) { /* if the buffer exists and has characters, copy them to user buffer */ if (anybuf(stream) stream-_cnt != 0) { if(stream-_cnt 0) { _ASSERTE((“Inconsistent Stream Count. Flush between consecutive read and write”, stream-_cnt = 0)); stream-_flag |= _IOERR; return (total – count) / elementSize; } /* how much do we want? (unsigned)count : stream-_cnt; if (nbytes dataSize) { if (bufferSize != SIZE_MAX) { memset(buffer, _BUFFER_FILL_PATTERN, bufferSize); } _VALIDATE_RETURN((“buffer too small”, 0), ERANGE, 0) } memcpy_s(data, dataSize, stream-_ptr, nbytes); /* update stream and amt of data read */ count -= nbytes; stream-_cnt -= nbytes; stream-_ptr += nbytes; data += nbytes; dataSize -= nbytes; } else if (count = streambufsize) { /* If we have more than streambufsize chars to read, get data by calling read with an integral number of bufsiz blocks. Note that if the stream is text mode, read will return less chars than we ordered. */ if (streambufsize) { /* In 64bit apps size_t is bigger than unsigned * (which is 32bit even in 64 bit machines), so * we need to split the read into INT_MAX chunks * since _read() only support up to _signed_ int * (even though the in parameter is unsigned). */ if (count INT_MAX) { /* calc chars to read — the largest multiple of streambufsize * smaller then INT_MAX */ nbytes = (unsigned)(INT_MAX – INT_MAX % streambufsize); } else { /* calc chars to read — (count/streambufsize) * streambufsize */ nbytes = (unsigned)(count – count % streambufsize); } } else { nbytes = (count INT_MAX)?(unsigned)INT_MAX: (unsigned)count; } if (nbytes dataSize) { if (bufferSize != SIZE_MAX) { memset(buffer, _BUFFER_FILL_PATTERN, bufferSize); } _VALIDATE_RETURN((“buffer too small”, 0), ERANGE, 0) } nread = _read(_fileno(stream), data, nbytes); if (nread == 0) { /* end of file — out of here */ stream-_flag |= _IOEOF; return (total – count) / elementSize; } else if (nread == (unsigned)-1) { /* error — out of here */ stream-_flag |= _IOERR; return (total – count) / elementSize; } /* update count and data to reflect read */ count -= nread; data += nread; dataSize -= nread; } else { /* less than streambufsize chars to read, so call _filbuf to fill buffer */ if ((c = _filbuf(stream)) == EOF) { /* error or eof, stream flags set by _filbuf */ return (total – count) / elementSize; } /* _filbuf returned a char — store it */ if (dataSize == 0) { if (bufferSize != SIZE_MAX) { memset(buffer, _BUFFER_FILL_PATTERN, bufferSize); } _VALIDATE_RETURN((“buffer too small”, 0), ERANGE, 0) } *data++ = (char) c; –count; –dataSize; /* update buffer size */ streambufsize = stream-_bufsiz; } } /* we finished successfully, so just return num */ return num; } 其中,int __cdecl _filwbuf ( FILE *str ) #endif /* _UNICODE */ { REG1 FILE *stream=NULL; /* In safecrt, we assume we always have a buffer */ _VALIDATE_RETURN(str != NULL, EINVAL, _TEOF); /* Init pointer to _iob2 entry. */ stream = str; if (!inuse(stream) || stream-_flag _IOSTRG) return(_TEOF); if (stream-_flag _IOWRT) { stream-_flag |= _IOERR; return(_TEOF); } stream-_flag |= _IOREAD; /* Get a buffer, if necessary. */ if (!anybuf(stream)) { #ifndef _SAFECRT_IMPL _getbuf(stream); #else /* _SAFECRT_IMPL */ /* In safecrt, we assume we always have a buffer */ _VALIDATE_RETURN(FALSE, EINVAL, _TEOF); #endif /* _SAFECRT_IMPL */ } else { stream-_ptr = stream-_base; } stream-_cnt = _read(_fileno(stream), stream-_base, stream-_bufsiz); #ifndef _UNICODE if ((stream-_cnt == 0) || (stream-_cnt == -1)) { #else /* _UNICODE */ if ((stream-_cnt == 0) || (stream-_cnt == 1) || stream-_cnt == -1) { #endif /* _UNICODE */ stream-_flag |= stream-_cnt ? _IOERR : _IOEOF; stream-_cnt = 0; return(_TEOF); } if ( !(stream-_flag (_IOWRT|_IORW)) ((_osfile_safe(_fileno(stream)) (FTEXT|FEOFLAG)) == (FTEXT|FEOFLAG)) ) stream-_flag |= _IOCTRLZ; /* Check for small _bufsiz (_SMALL_BUFSIZ). If it is small and if it is our buffer, then this must be the first _filbuf after an fseek on a read-access-only stream. Restore _bufsiz to its larger value (_INTERNAL_BUFSIZ) so that the next _filbuf call, if one is made, will fill the whole buffer. */ if ( (stream-_bufsiz == _SMALL_BUFSIZ) (stream-_flag _IOMYBUF) !(stream-_flag _IOSETVBUF) ) { stream-_bufsiz = _INTERNAL_BUFSIZ; } #ifndef _UNICODE stream-_cnt–; return(0xff *stream-_ptr++); #else /* _UNICODE */ stream-_cnt -= sizeof(wchar_t); return (0xffff *((wchar_t *)(stream-_ptr))++); #endif /* _UNICODE */ } 代码中分了三种情况:1) 缓冲区不为空此时, 把缓冲区中的数据复制到传入的字符数组中. 2) 缓冲区为空, 需要读取的数据大于缓冲的尺寸此时, 直接调用函数_fread把文件中的内容写到传入的字符数组中. 3) 缓冲区为空, 需要读取的数据不大于缓冲的尺寸此时, 调用函数_fread读满缓冲区, 并再写缓冲区的一个字符到传入的字符数组中. 若未读满传入的字符数组, 循环执行上述1~3过程, 直到读满或读到文件末尾(EOF).

c语言中fread函数怎么用

c语言中fread函数语法为size_t fread( void *restrict buffer, size_t size, size_t count, FILE *restrict stream )。buffer是指向要读取的数组中首个对象的指针,size是每个对象的大小(单位是字节),count是要读取的对象个数,stream是输入流。通过fread函数可进行数据读取,返回成功读取的对象个数。

扩展资料:

fread函数从给定输入流stream读取最多count个对象到数组buffer中(相当于以对每个对象调用size次fgetc),把buffer当作unsignedchar数组并顺序保存结果。流的文件位置指示器前进读取的字节数。

若出现错误,则流的文件位置指示器的位置不确定。若没有完整地读入最后一个元素,则其值不确定,可能小于count。若size或count为零,则fread返回零且不进行其他动作。fread不区分文件尾和错误,因此调用者必须用feof和ferror才能判断发生了什么。

读取文件c语言fread的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于c语言 读文件、读取文件c语言fread的信息别忘了在本站进行查找喔。

本文来自投稿,不代表【】观点,发布者:【

本文地址: ,如若转载,请注明出处!

举报投诉邮箱:253000106@qq.com

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2024年4月3日 05:23:00
下一篇 2024年4月3日 05:29:12

相关推荐

  • c语言改写模式,c语言实现修改功能

    c语言程序修改? 1、这个程序有4个错误,我都加粗了,第一个是m没有赋初值,第二个是while表达式中的ch=getchar()需要括号括起来,第三个是m=m*10+ch-0中的0也需要用单引号括起来,第四个是第2个while中为m!=0。 2、define容易造成误会,因为不符合一般的编程习惯,false 0, true 1;scanf放在你的那个地方是达…

    2024年5月23日
    3900
  • c语言控制代码的换码序列,c语言交换代码

    求C语言编程大神解答一下下面这个编程代码? k==5,用5去除125余0,所以r=125%5中r为0。由于!0为1,所以执行while循环体:先打印出5(k的值),再n=n/k==125/5=25;由于251则再打印出*号。这一循环结果输出是5*。 下面是我的代码,三个函数分别对应三个问题。 在实现基本要求的前提下,拓展了可以从键盘输入的功能,以下为各题代码…

    2024年5月23日
    5600
  • linux给文件写权限,linux怎么给文件权限

    linux宝塔写入权限不足 1、可以使用chmod命令修改权限。语法:chmod [-cfvR] [–help] [–version] mode file…说明 : Linux/Unix 的档案调用权限分为三级 : 档案拥有者、群组、其他。利用 chmod 可以藉以控制档案如何被他人所调用。 2、通过更改文件权限可以使用c…

    2024年5月23日
    5100
  • c语言扫描io脚状态,c语言端口扫描

    求51单片机的上升沿和下降沿C语言检测程序列子,端口就是普通IO口。 上升沿触发是当信号有上升沿时的开关动作,当电位由低变高而触发输出变化的就叫上升沿触发。也就是当测到的信号电位是从低到高也就是上升时就触发,叫做上升沿触发。 单片机怎么计算1s内下降沿的个数的C语言程序或者计算两个下降沿的时间(检测脉冲频率)计算1s内下降沿的个数方法是,一个定时器设置定时1…

    2024年5月23日
    4400
  • c语言mallloc使用的简单介绍

    C语言中使用malloc必须加#includemallo.h? 1、在C语言中使用malloc函数进行动态内存分配。malloc的全称是memory allocation,中文叫动态内存分配。原型:extern void malloc(unsigned int num_bytes);功能:分配长度为num_bytes字节的内存块。 2、你可以看一下C语言那本…

    2024年5月23日
    4400
  • c语言三位小数,C语言三位小数

    怎样用C++语言输出精确到小数点后三位的数? 1、用C++语言输出精确到小数点后三位的数,可以参考下面给出的代码:coutsetiosflags(ios:fixed)setprecision(3)。其中 setiosflags中set是设置的意思。ios是iostream的缩写,即输入输出流。flags是标志的意思。 2、要精确到小数点后若干位,则数据类型为…

    2024年5月23日
    7300
  • c语言21点游戏,二十一点游戏代码c语言

    如何使用C语言编写简单小游戏? 1、数学知识:长方形的面积S=a*b 长方形周长L=2*(a+b)其中a b分别为长方形的宽和高。算法分析:长方形面积及周长均依赖于宽和高,所以先要输入宽高值,然后根据公式计算,输出结果即可。 2、/*也不知道你是什么级别的,我是一个新手,刚接触编程语言,以下是我自己变得一个小程序,在所有c语言的编译器(vc++0、turbo…

    2024年5月23日
    6400
  • c语言当中的null,C语言当中的符号

    C/C++中,NULL和null的区别是什么? nul 和 null要看编译器,不同的编译器有所区别。 所以C或者C++中都使用一个特殊定义NULL表示无效值,其本质就是未定义具体数据类型的0值。 null是是什么都没有的意思。在java中表示空对象。 本意是“空的;元素只有零的”意思。计算机中通常表示空值,无结果,或是空集合。\x0d\x0a在ASCII码…

    2024年5月23日
    4500
  • 包含c语言对txt文件命名的词条

    如何在C语言编程里面修改源文件名字 如果你是在WINDOWS的话,简单了,随便用个编辑器,比如记事本,然后写c源程序,保存到你想要保存的位置。如果你在DOS下,可以用edit,写好以后,按alt键,选择文件菜单,然后保存。 用open打开文件,注意操作模式使用“修改”或者“添加” 用write或者fprintf向文件中写入你的内容。 用close关闭文件。 …

    2024年5月23日
    4900
  • 学c语言编程,学c语言编程用什么软件

    编程开发必须要学C语言吗? 1、要学习。编程开发的学习内容主要包括c语言、python和c+语言。C语言作为一种简单灵活的高级编程语言,它是一个面向过程的语言,一般是作为计算机专业的基础入门语言课程。 2、C语言。对于刚接触编程的人来说,先学习C语言是非常重要的。C语言可以说是是计算机编程语言的鼻祖,其他的编程语言几乎全是由C语言变化衍生出来的。 3、不需要…

    2024年5月23日
    3500

发表回复

登录后才能评论



关注微信