关于读取文件c语言fread(c语言 读文件)话题,今日,嗨壳技术分享网小编抽出大半天的时间整理一些读取文件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.
”);
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
”,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
”,numwritten);
fclose(stream);
}
else
printf(“Problem opening the file
”);
if ((stream=fopen(“fread.out”,”r+t”))!=NULL)
{
numread=fread(list,sizeof(char),25,stream);
printf(“Number of items read =%d
”,numread);
printf(“Contents of buffer=%.25s
”,list);
fclose(stream);
}
else
{
printf(“File could not be opened
”);
}
system(“pause”);
return 0;
}
程序员的自我修养: 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的信息别忘了在本站进行查找喔。
以上【 读取文件c语言fread(c语言 读文件) 】是嗨壳技术分享网(www.heikehao.com)编辑整理。嗨壳技术分享网包含技术投稿、C语言、Excel、Java、Linux、网络安全和账号安全等丰富的栏目,并分享一些互联网安全技术知识和安全防护经验,帮助网友注重网络安全,让网络安全不再是问题。
原创文章,作者:语言我知,如若转载,请注明出处:https://www.heikehao.com/310.html