本文介绍了如何找到文件的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在阅读 a文件时找到文件结束条件的正确方法是什么? feof()如何检测文件末尾是到达了吗? 这是否需要操作系统的支持? 提前获得任何帮助... 解决方案 如果文件是用OS实现的,feof()将依赖OS报告这样的读取操作的a条件。 如果文件在C库中实现,操作系统不是问题。 重要的是要注意feof()是违反直觉的: - 是否达到文件末尾的读操作设置条件是 未指定:fgets()读取最后一行将可能没有设置它,而 fscanf()吃掉尾随空格可能。 - 如果文件是由另一个函数写入的(或者进程在哪里创建 sense),feof()可能会返回非0,即使有更多数据可用于 读取(阅读前可能需要clearerr()或fseek())。 根据经验,在读取操作失败后,只使用feof()消除文件结尾的读取错误 。 成语,例如while(!feof(f)){...}和do {...} while(!feof(f));是b bogus,必须避免。 - Chqrlie。 PS:我知道7.19.6.2示例3节19节。这段代码snipplet是伪造的,而b 无用。无论如何,AAMOF大多数do / while循环都是假的。 使用feof()更容易。 FILE * fp = fopen(... ); while(!feof(fp)){ ...读取的东西 } 当然,正如之前的海报所说,你可能有一个简短的数字或 甚至是一个错误,所以考虑到这一点。 while(!feof(fp)){ / *短计数? * / n = fread(buffer,...,fp); if(n!= whatever){ if(ferror()) ...某种错误 if(feof()) ...文件结尾 } } What is the proper way of finding an end of file condition while readinga file ? How does feof() detects that end of file is reached ?Does this require support from OS ? Thanx in advance for any help ... 解决方案 if files are implemented with the OS, feof() will rely on the OS reporting sucha condition for read operations.if files are implemented within the C library, the OS is not an issue. It is important to notice that feof() is counterintuitive:- Whether a read operation that reaches the end of a file set the condition isnot specified : fgets() reading the last line will probably not set it, whilefscanf() eating trailing white space might.- If the file is being written by another function (or process where that makessense), feof() may return non 0 even after more data becomes available forreading (clearerr() or fseek() may be needed before reading). As a rule of thumb, only use feof() to disambiguate end of file from read errorafter a read operation fails.Idioms such as while (!feof(f)) { ... } and do { ... } while (!feof(f)); arebogus and must be avoided. --Chqrlie. PS: I know about 7.19.6.2 example 3 verse 19. This code snipplet is bogus anduseless. AAMOF most do/while loops are bogus anyway. Using feof() is easier though. FILE *fp = fopen(...); while (!feof(fp)) {... read stuff} And of course as the previous poster said, you may have a short count oreven an error, so take that into account. while (!feof(fp)) { /* Short count ? */n = fread(buffer, ..., fp); if (n != whatever) {if (ferror())... some kind of errorif (feof())... end of file}} 这篇关于如何找到文件的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-26 04:32