Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!icd.ab.com!iccgcc.decnet.ab.com!bush From: bush@iccgcc.decnet.ab.com Newsgroups: comp.lang.c Subject: RE: fscanf(), fgets(), fflush() problem Message-ID: <1991Jun24.132920.4956@iccgcc.decnet.ab.com> Date: 24 Jun 91 18:29:20 GMT Lines: 59 Date: 24 Jun 91 12:44:00 EDT From: " 24960, BUSH,STEVEN" Subject: fflush()? fscanf() fgets() problem. To: "whitbeck" X-News: iccgcc comp.lang.c:10700 >From: whitbeck@sanjuan.wrcr.unr.edu (Mike Whitbeck) >Subject:fflush()? fscanf() fgets() problem. >Date: 31 May 91 06:44:57 GMT >Message-ID:<456@equinox.unr.edu> >I have a problem using fscanf() and fgets() and was wondering >if it had something to do with fflush() {I guess I just don't >know what fflush() is for!} > >I open a file > fp = fopen("file","r"); > >and then I read some stuff > fscanf(fp,"%f\n",&fv); >then later I try to suck in a line as a text string > fgets(str,n,fp); >Elsewhere I have used fgets() to read in a line >but here it fails! (gets only the first 'word' (whitespace >delimited) from the line. >As a workaround I use a loop > for (...) { > fscanf(fp,"%s",dummy); > strcat(line," "); > strcat(line,dummy); > } >ICK! > >What's going on here? Is fscanf() known to mess up fgets()? or >is this unique to me? [I am using a SUN 3/80]. > >HELP! The problem that you speak of is a common pitfall that most C programmers experience at some point in time. The problem is not really a problem. The function fscanf() is much like the function scanf(). fscanf() like scanf() stops reading input at the newline character. At that point in time, the newline character is still in the input buffer, and is NOT read. fgets() on the other hand reads everything including the newline character. If you follow a call to fscanf() by a call to fgets(), all fgets() will read is the newline character that fscanf() doesn't scan. The result looks as if fgets() fails when all it read was a newline. One way around this side effect is to always follow scanf() or fscanf() by getc() or fgetc() like the following: fscanf("%f",&float_value); /* read a floating point value */ fgetc(stdin); /* read the newline character */ fgets(string_array); /* read a string */ The fflush() function is used only to flush output buffers to disk. When working with files, output information goes into a disk buffer, which when full, is flushed to disk by the operating system. All that fflush() does is to allow you to force the operating system to write a disk buffer to disk when it is not completely full.