慕标琳琳
如何检测EOF取决于您用来读取流的内容:function result on EOF or error -------- ----------------------fgets() NULLfscanf() number of succesful conversions less than expectedfgetc() EOFfread() number of elements read less than expected检查输入调用的结果是否符合上述适当条件,然后调用feof()以确定结果是否是由于击中EOF或其他错误而导致的。使用fgets(): char buffer[BUFFER_SIZE]; while (fgets(buffer, sizeof buffer, stream) != NULL) { // process buffer } if (feof(stream)) { // hit end of file } else { // some other error interrupted the read }使用fscanf():char buffer[BUFFER_SIZE];while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion{ // process buffer}if (feof(stream)) { // hit end of file}else{ // some other error interrupted the read}使用fgetc():int c;while ((c = fgetc(stream)) != EOF){ // process c}if (feof(stream)){ // hit end of file}else{ // some other error interrupted the read}使用fread():char buffer[BUFFER_SIZE];while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 // element of size // BUFFER_SIZE{ // process buffer}if (feof(stream)){ // hit end of file}else{ // some other error interrupted read}请注意,所有形式都相同:检查读取操作的结果;如果失败,则检查EOF。您会看到很多示例,例如:while(!feof(stream)){ fscanf(stream, "%s", buffer); ...}这种形式不工作的人认为它的方式,因为feof()之前将不会返回true 后,你已经尝试读取过去的文件的末尾。结果,循环执行的次数过多,这可能会或可能不会引起您的痛苦。