• Welcome to Powerbasic Museum 2020-B.
 

ProgEx21 - Problems With scanf In Reading File Data

Started by Frederick J. Harris, November 08, 2009, 04:40:24 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris

/*
  ProgEx21   --  Reason why I'm stuck!  (program should run as C or C++)
 
  In ProgEx20 we showed how to write a comma delimited text file.  In this
  program I write my name out to a text file and attempt to read it back in with
  fscanf, which is something of a counterpart to BASIC's Input #fp statement -
  but not quite.  As you can see in the output below - or in real life if you
  run the program, only my first name comes back out of the file!  Not good! 
  You might be able to guess what happened.  The fscanf (with files) or scanf
  breaks at white space and doesn't give a hoot about commas! 
 
  However, fscanf and scanf can be useful.  Lets take a short look at scanf and
  fscanf before tackling classes.  Continued in ProgEx22.     
*/

#include <stdio.h>

int main(void)
{
char szBuffer[]="Frederick John Harris";
FILE* fp;

fp=fopen("Data.dat","w");     //Same as Open "Data.dat" For Output As #fp
fprintf(fp,"%s\n",szBuffer);  //Same as Print #fp, szBuffer
fclose(fp);                   //Same As Close #fp
fp=fopen("Data.dat","r");     //Same as Open "Data.dat" For Input As #fp
fscanf(fp,"%s",szBuffer);     //Not the same as...Input #fp, szBuffer  !!!
printf("%s",szBuffer);        //Same as Print szBuffer
fclose(fp);                   //Same as Close #fp
getchar();                    //Same as Waitkey$

return 0;                     //Same as PBMain=0
}

/*  --Output--
==============
Frederick
*/