Can I read the data by fscanf function from a file where data is written by fwrite ?

This is a discussion on Can I read the data by fscanf function from a file where data is written by fwrite ? within the C Programming forums, part of the General Programming Boards category; I think its not possible because fwrite writes the data in binary form and fscanf reads text data. Pls reply...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    61

    Can I read the data by fscanf function from a file where data is written by fwrite ?

    I think its not possible because fwrite writes the data in binary form and fscanf reads text data. Pls reply

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Do you know the difference between text and binary modes? It is possible, results may not be what is expected.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    fwrite writes ANY type of data to your file, it may be text or binary. fscanf reads "text" and translates it to the types you want. If the input to fscanf is not text, then "anything" can happen - most likely "not what you wanted" (because there is an almost infinite variety of "not right", but usually only one "right").

    So the answer is "it depends". But most likely, you want to use fread to fetch data written with fwrite. That's the "natural" method.

    But if you have a text-string or list of numbers in text-form that is written with fwrite, then you can certainly read it with fscanf. If you have a binary integer, it's not going to come back "right" by using fscanf.

    --
    Mats

  4. #4
    Registered User
    Join Date
    Aug 2007
    Posts
    26
    And if my data file are numbers in a "matrix form", i.e., organiced in several rows and columns, when a called fscanf the function will save each data of the file in a compoment of a two dimensional array, say loquesea[Nume][Number2]?

  5. #5
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    I don't understand this last question. fscanf() just reads data as text and tries to parse it as you tell it. It stores each value into each variable you give it, provided all goes well. You can have data arranged anyway you want in the file. fscanf() behaves the same way each time, assuming nothing about the data that you have except what you tell it.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    if your code to write the data looks like this:

    Code:
    int loquesea[10][3];
    ...
       fwrite(loquesea, sizeof(loquesea), 1, somefile);
    ...
    then your read should look similar, changing to fread insead of fwrite.

    If there is processing to make a text-string out of loquesa, then you could use fscanf().

    [The datatype of loquesa wouldn't really change matters if it's int, long, char, float, double or some struct - it still would require a fread to read it, unless the data is processed to become text]

    --
    Mats

  7. #7
    Registered User
    Join Date
    Aug 2007
    Posts
    26
    Ok; thanks a lot. (I love C xD)

  8. #8
    Registered User
    Join Date
    Nov 2006
    Posts
    61

    Can anyone reply?

    I think its not possible because fwrite writes the data in binary form and fscanf reads text data. Pls reply

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    It's always possible to contrive an fwrite() which can then be read with fscanf(), but for the most part, you use fread()/fwrite() and fprintf()/fscanf() as matched pairs.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    To expand a bit on Salem's reply: fwrite writes the data you give it. If you give it a set of strings like this:
    "1 Mats PO73EP\n"
    then fscanf can read it.

    If you give it a struct of this sort:
    Code:
    struct {
        int number;
        char name[10];
        char postcode[8];
    };
    then fscanf can't (without A LOT of contortion) [1] be made to read it.


    [1] Using some sort of convoluted construction with many %c, you could PERHAPS do it - but it's quite likely that it will not work reliably at all, and it will certainly not be easy to use nor will it be asy to modify, should you need to add "housenumber" to the list of items in the struct.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Registered User
    Join Date
    Aug 2007
    Posts
    26
    Hello again; I revive this topic.

    This is the problem: I create a data file, with NSTEPS rows and DIM columns, but I cannot read it using fscanf.

    My code is as follows:

    Code:
     for(i = 0; i < NSTEPS; i++){
        for(j = 0; j < DIM; j++){
    
          fscanf( fp, "&#37;f \n ", &a[i][j]);
        }
      }
    I know it is not reading it because I then try to print a[i][j], and all I get is zeros, numbers I don't know where came from, and long strings of digits!

    The numbers in the data file are double, and obviusle I define a[NSTEPS][DIM] as double.

    Thanks!

  12. #12
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    Maybe try &#37;lf then as the conversion, because that is what a double needs - see the manual.

    Also, the trailing " \n " of the format adds nothing, "%lf" will suffice.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  13. #13
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,239
    Quote Originally Posted by forumuser View Post
    I think its not possible because fwrite writes the data in binary form and fscanf reads text data. Pls reply
    There is no such thing as "binary form." There is a concept of opening a file in "binary mode" but that's not the issue here. fwrite() and fprintf() both write data to a file. fscanf() reads and formats textual information. If you use fwrite() to write textual information, there is no reason you cannot use fscanf() to read it back in.

    Forget this binary vs. text stuff. It has nothing to do with this.

  14. #14
    Registered User
    Join Date
    Aug 2007
    Posts
    26
    It does't work. My data file, wrt.dat, has the first two lines with two numbers: the first is the number if rows, and the second, the number of colums. My code is like this:

    Code:
    int main(){
    
      double **a;
      int i,j;
      int *NSTEPS,*DIM;
      FILE *fp;
      fp=fopen( "wrt.dat", "r");
     
      fscanf(fp, "&#37;d \n", NSTEPS);  /* read number of points */
      fscanf(fp, "%d \n", DIM);  /* read dimension */A
    
      a = malloc( NSTEPS * sizeof( double *));
    
      if ( a == NULL ) {
        printf("No hay ubicaci&#243;n de memoria suficiente");
        exit(0);
      }
    
      for (i = 0;  i < NSTEPS; i++) {
        a[i] = malloc( DIM * sizeof(double));
      
        if (a[i] == NULL) {
          printf("No hay ubicaci&#243;n de memoria suficiente");
          exit(0);
        }
      }
    
    
      for(i = 0; i < *NSTEPS; i++){
        for(j = 0; j < *DIM; j++){
           fscanf(fp,  "%lf ",  &a[i][j] );
           printf( "%f", a[i][j] );
        }
        printf("\n");
      }
    
      fclose(fp);
      return 0;
    }
    I really don't understand where the failure is; i have found some code using fscanf just like me, and they are supposed to work.
    Last edited by Isolda_; 11-01-2007 at 12:44 PM.

  15. #15
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,239
    Quote Originally Posted by Isolda_ View Post
    It does't work. My data file, wrt.dat, has the first two lines with two numbers: the first is the number if rows, and the second, the number of colums. My code is like this:
    Your NSTEPS and DIM pointers are pointing to nowhere. Instead, declare them as:

    Code:
    int nsteps, dim;
    Notice I made these lower-case. You should avoid all uppercase names for anything except preprocessor macros.

    And call fscanf() as:

    Code:
    fscanf(fp, "&#37;d", &nsteps);  /* read number of points */
    fscanf(fp, "%d", &dim);  /* read dimension */

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  4. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21