由于无限循环而陷入功能

时间:2015-03-24 14:32:14

标签: c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void dossier (FILE*f,FILE*f2)
{
    char k ;

    k=fgetc(f) ;
    fputc(k,f2) ;
    printf("here%c",k) ;

    while ( k!='\\')
    {
        k=fgetc(f);
        fputc(k,f2);
    }
}

void dossierp(FILE*f,FILE*f2)
{
    char ch [1000] ;
    do
    {
        dossier(f,f2) ;
    }
    while (fgets(ch,1000,f) !=NULL) ;
}

int main()
{

    FILE*f=NULL ;
    FILE*f2=NULL ;
    f = fopen("text.txt","r+") ;
    f2= fopen("t.txt","r+") ;
    dossierp(f,f2);
    fclose(f);
    fclose(f2);

    return 0;
}

文件f包含行。每一行都采用这种形式&#34; (text)\text2)\...\&#34;。文件f2为空,函数dossier有效,但dossierp无效,因为它有无限循环。为什么?

2 个答案:

答案 0 :(得分:1)

我认为您的问题是您无法处理EOF中的dossier。因此,在某些情况下,无限循环将位于dossier函数中,而不是dossierp函数中。

请注意,getc会返回int,而不是charchar无法代表EOF

答案 1 :(得分:0)

The function has a problem because 

when dossierp calls dossier 
then reads the rest of the line, the EOF indication is NOT set

the dossirp then jumps to the top of the loop 
and calls dossier
but the fgetc results are not being checked for EOF
so they keep on trying to read characters, and always failing
so that is where the infinite loop is at.

suggest adding a check of the results of each call to fgetc 
for EOF and exiting the function when EOF is encountered,
returning an indication to dossierp that EOF was encountered
so dossierp can exit its loop and exit the function.

Note: reading the last line (or last character) of a file
      does not set EOF.
      Rather trying to read past the last line (or last char)
      of a file sets EOF.

 Note: EOF is an integer, so the fgetc() return variables must
       be int, not char

 a few minutes with a debugger and attention to what 
 each function returns when EOF is encountered
 (and/or an error is encountered)
 would have made finding the root of this problem very easy.
相关问题