#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
无效,因为它有无限循环。为什么?
答案 0 :(得分:1)
我认为您的问题是您无法处理EOF
中的dossier
。因此,在某些情况下,无限循环将位于dossier
函数中,而不是dossierp
函数中。
请注意,getc
会返回int
,而不是char
。 char
无法代表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.