im facing problem with fread()??

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rajshekhar

    im facing problem with fread()??

    Hi ,
    i am writing a simple prgm to read a .txt file then store the contents
    into the array...
    program as follows:
    --------------------------
    #include<stdio. h>

    int main()
    {
    FILE *fp1;
    int buf[5];
    int num,i;

    fp1=fopen("tria ngle.txt","r");
    if(fp1 == NULL)
    {
    printf("file cant be opend");
    exit(0);
    }

    num=fread(buf,s izeof(int),5,fp 1);
    printf("num of elements read =%d\n",num);

    for(i=0;i<5;i++ )
    printf("%d\n",b uf[i]);
    return 0;
    }

    ------------------
    i am getting no.of elements read as 0,but file is openable...
    the elements as junk numbers...

    can anybody tell me wat is the problem in doing this ..????
    is it that i m using fread wrongly or it behaves abnoramlly???

    TIA
    Regards,
    Rajshekhar

  • Kuku

    #2
    Re: im facing problem with fread()??

    The file triangle.txt must be empty that's why it is returning 0 number
    of elements and junk value there on
    Rajshekhar wrote:[color=blue]
    > Hi ,
    > i am writing a simple prgm to read a .txt file then store the contents
    > into the array...
    > program as follows:
    > --------------------------
    > #include<stdio. h>
    >
    > int main()
    > {
    > FILE *fp1;
    > int buf[5];
    > int num,i;
    >
    > fp1=fopen("tria ngle.txt","r");
    > if(fp1 == NULL)
    > {
    > printf("file cant be opend");
    > exit(0);
    > }
    >
    > num=fread(buf,s izeof(int),5,fp 1);
    > printf("num of elements read =%d\n",num);
    >
    > for(i=0;i<5;i++ )
    > printf("%d\n",b uf[i]);
    > return 0;
    > }
    >
    > ------------------
    > i am getting no.of elements read as 0,but file is openable...
    > the elements as junk numbers...
    >
    > can anybody tell me wat is the problem in doing this ..????
    > is it that i m using fread wrongly or it behaves abnoramlly???
    >
    > TIA
    > Regards,
    > Rajshekhar[/color]

    Comment

    • Rajshekhar

      #3
      Re: im facing problem with fread()??

      no its not empty ....!!
      i read the contents of it using,,,,,getc & printed them using putc

      ~Rajshekhar

      Comment

      • manoj1978@gmail.com

        #4
        Re: im facing problem with fread()??


        Rajshekhar wrote:[color=blue]
        > Hi ,
        > i am writing a simple prgm to read a .txt file then store the contents
        > into the array...[/color]
        Please post the contents of triangle.txt.th en someone can help you.
        If triangle.txt is a binary file then try rb instead of r in fopen.
        [color=blue]
        > program as follows:
        > --------------------------
        > #include<stdio. h>
        >
        > int main()
        > {
        > FILE *fp1;
        > int buf[5];
        > int num,i;
        >
        > fp1=fopen("tria ngle.txt","r");
        > if(fp1 == NULL)
        > {
        > printf("file cant be opend");
        > exit(0);
        > }
        >
        > num=fread(buf,s izeof(int),5,fp 1);
        > printf("num of elements read =%d\n",num);
        >
        > for(i=0;i<5;i++ )
        > printf("%d\n",b uf[i]);
        > return 0;
        > }
        >
        > ------------------
        > i am getting no.of elements read as 0,but file is openable...
        > the elements as junk numbers...
        >
        > can anybody tell me wat is the problem in doing this ..????
        > is it that i m using fread wrongly or it behaves abnoramlly???
        >
        > TIA
        > Regards,
        > Rajshekhar[/color]

        Comment

        • Rajshekhar

          #5
          Re: im facing problem with fread()??

          hi
          the file triangle.txt contents are...
          6 6 4

          thats it .....
          i dont think this file is binary file ..!!!

          Comment

          • Villy Kruse

            #6
            Re: im facing problem with fread()??

            On 24 Aug 2005 03:30:51 -0700,
            manoj1978@gmail .com <manoj1978@gmai l.com> wrote:

            [color=blue]
            >
            > Rajshekhar wrote:[color=green]
            >> Hi ,
            >> i am writing a simple prgm to read a .txt file then store the contents
            >> into the array...[/color]
            > Please post the contents of triangle.txt.th en someone can help you.
            > If triangle.txt is a binary file then try rb instead of r in fopen.
            >[/color]

            The way fread() in program is used strongly suggests that the file has
            to be binary. A text file is better read using fscanf(), or a combination
            of fgets() and sscanf(), or som variant of getc()/getchar().

            Villy

            Comment

            • Villy Kruse

              #7
              Re: im facing problem with fread()??

              On 24 Aug 2005 03:34:16 -0700,
              Rajshekhar <rajshekhar3@gm ail.com> wrote:

              [color=blue]
              > hi
              > the file triangle.txt contents are...
              > 6 6 4
              >
              > thats it .....
              > i dont think this file is binary file ..!!![/color]


              If sizeof(int) on your system is greater than the total number of bytes
              in the input file there are not enough data for even the first element,
              and thus you read zero elements.

              Villy

              Comment

              • Cong Wang

                #8
                Re: im facing problem with fread()??


                Rajshekhar wrote:[color=blue]
                > hi
                > the file triangle.txt contents are...
                > 6 6 4
                >
                > thats it .....
                > i dont think this file is binary file ..!!![/color]
                No,you are wrong!That depends on how you treat it!If you want to open
                is as a binary file,it is a binary file!Text files are similar.

                Comment

                • Nick Keighley

                  #9
                  Re: im facing problem with fread()??

                  Rajshekhar wrote:
                  [color=blue]
                  > i am writing a simple prgm to read a .txt file[/color]

                  if it's a text file use fgets() rather than fread()

                  [color=blue]
                  > then store the contents
                  > into the array...
                  > program as follows:
                  > --------------------------
                  > #include<stdio. h>[/color]

                  #include <stdio.h>

                  [color=blue]
                  > int main()[/color]

                  int main (void)
                  [color=blue]
                  > {
                  > FILE *fp1;
                  > int buf[5];
                  > int num,i;
                  >
                  > fp1=fopen("tria ngle.txt","r");
                  > if(fp1 == NULL)
                  > {
                  > printf("file cant be opend");
                  > exit(0);
                  > }
                  >
                  > num=fread(buf,s izeof(int),5,fp 1);
                  > printf("num of elements read =%d\n",num);
                  >
                  > for(i=0;i<5;i++ )
                  > printf("%d\n",b uf[i]);[/color]

                  here we have a fundamental misconception. Lets suppose your file looks
                  like this:
                  3 4 5

                  I'm guessing your program wants to read three numbers (because it's
                  called triangle.txt). If you read raw binary and your file is in ASCII
                  you'll actually read the following bytes:
                  51 32 52 32 53

                  So you need to convert these bytes into numbers (or use %c istead of %d
                  in the above printf()). Try this:-

                  if (scanf (buf "%d %d %d", &j, &k, &m) != 3)
                  {
                  printf ("can't parse line\n");
                  exit (1);
                  }
                  else
                  printf ("read %d, %d %d\n", j, k, m);

                  declare j, k and m as int

                  [color=blue]
                  > return 0;
                  > }
                  >
                  > ------------------
                  > i am getting no.of elements read as 0,but file is openable...
                  > the elements as junk numbers...[/color]

                  hmm. I only just noticed this. I don't know what your file looks like.
                  I don't know what "junk number" are. You've told it read five lots of
                  4 bytes (assuming 32-bit ints). Probably not what you meant. That won't

                  fit in a 5 bytes array. Really do change over to fgets(). fread() is
                  for binary data. fread() may not handle end of line and end of file
                  correctly.
                  [color=blue]
                  > can anybody tell me wat is the problem in doing this ..????
                  > is it that i m using fread wrongly or it behaves abnoramlly???[/color]

                  I suggest you get a good book. Eg. K&R.


                  --
                  Nick Keighley

                  Quantum Boggum Sort:
                  Q1. use a source of quantum noise (eg. radioactive decay) to
                  randomly permutate an array.
                  Q2. if the array is not ordered, destroy the universe (*)
                  Q3. if you reached this step your universe has sorted the array
                  in O(n) time.

                  (*) [100] this is left as a exercise

                  Comment

                  • Christopher Benson-Manica

                    #10
                    Re: im facing problem with fread()??

                    Rajshekhar <rajshekhar3@gm ail.com> wrote:
                    [color=blue]
                    > #include<stdio. h>[/color]

                    The prototype for exit() is in stdlib.h, which you forgot to include.
                    [color=blue]
                    > int main()
                    > {
                    > FILE *fp1;
                    > int buf[5];
                    > int num,i;[/color]
                    [color=blue]
                    > fp1=fopen("tria ngle.txt","r");[/color]
                    [color=blue]
                    > num=fread(buf,s izeof(int),5,fp 1);[/color]

                    Consider what you are doing here. You are asking for the first sizeof
                    int * 5 bytes of the file (probably 20); if the file contains 6 4 4,
                    buf[0] will contain four bytes that correspond to the internal
                    representations of '6', ' ', and '4'. As already noted, you'd be much
                    better off reading the contents of this file using fgets() and using
                    strtol() and friends to get your integers.
                    [color=blue]
                    > printf("num of elements read =%d\n",num);[/color]
                    [color=blue]
                    > for(i=0;i<5;i++ )[/color]

                    As a side note, if you know you read num bytes from the file, why not
                    iterate num times through buf?
                    [color=blue]
                    > printf("%d\n",b uf[i]);
                    > return 0;
                    > }[/color]

                    --
                    Christopher Benson-Manica | I *should* know what I'm talking about - if I
                    ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

                    Comment

                    • l4learn@gmail.com

                      #11
                      Re: im facing problem with fread()??

                      Hello ...
                      In the above code the file is not closed ....use something like
                      fcloseall() at the least to at the end of the programs where u use
                      files ..

                      the problem with ur program is here

                      #include<stdio. h>




                      ----> num=fread(buf,s izeof(int),5,fp ­1); /*this takes in values in
                      ascii format .. and stores the ascii values ...
                      printf("num of elements read =%d\n",num);


                      for(i=0;i<5;i++ )
                      printf("%d\n",b uf[i]); /* here use %c to print the numbers .. it
                      will convert the ascii to their corresponding chars ... that is the
                      numbers u want .. */
                      return 0;
                      /*fcloseall() or fclose(fp1); here please


                      }


                      i didnot wish to offend any one by this mail.....

                      Comment

                      • P.J. Plauger

                        #12
                        Re: im facing problem with fread()??

                        <l4learn@gmail. com> wrote in message
                        news:1124900074 .431082.319110@ f14g2000cwb.goo glegroups.com.. .

                        In the above code the file is not closed ....use something like
                        fcloseall() at the least to at the end of the programs where u use
                        files ..

                        the problem with ur program is here

                        #include<stdio. h>

                        A conforming C implementation closes all files at program shutdown.
                        It also does *not* contain a call to fcloseall, which is not part
                        of the C Standard.

                        P.J. Plauger
                        Dinkumware, Ltd.



                        Comment

                        • Jason Curl

                          #13
                          Re: im facing problem with fread()??

                          Rajshekhar wrote:[color=blue]
                          > hi
                          > the file triangle.txt contents are...
                          > 6 6 4
                          >
                          > thats it .....
                          > i dont think this file is binary file ..!!!
                          >[/color]

                          Rajshekhar, please quote what you're replying to in your message. I for
                          one can't always see what it is you're replying to, so sometimes your
                          reply looks like gibberish without context. You'll see this mentioned
                          often in the newsgroup if you've been reading for some time. It makes it
                          much more difficult for people to answer you (and decreases the
                          likelihood that they do)

                          Looking at the prototype for fread, it is:

                          size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

                          Based on your program, it tries to read 5*(sizeof int) from the file.
                          That's because it doesn't care about spaces, commas or other
                          punctuation. For that you should look at some other functions such as
                          fscanf, or write your own parser (much more recommended). There have
                          been numerous posts to this newsgroup asking the same question you have
                          in the last month - so please go have a look.

                          I don't know what the size of an int is on your machine, but it's
                          probably 4 or 8.

                          From the description I have of 'fread', it says:
                          "The function fread reads nmemb elements of data, each size bytes
                          long, from the stream pointed to by stream, storing them at the location
                          given by ptr."

                          This means, if your file has the contents:

                          6 6 4

                          This looks like (in binary)

                          0x36 0x20 0x36 0x20 0x34 (values are in hex)

                          So, I expect the first value to be something like 0x36203620 or
                          0x20362036 depending on the endianness of your machine (one big hex
                          number, that probably looks random).

                          The fact that you're getting a result of zero from fread() might be
                          because sizeof int is 8 bytes (there aren't 8 bytes in your file
                          triangle.txt).

                          Indeed, when I compile your program, I get the result:
                          num of elements read =1
                          540418102
                          134482484
                          -1075253336
                          134513429
                          0

                          Now ignoring the last 4 digits (because num=1), converting 540418102 to
                          hex we have exactly 0x20362036 (I'm running an Intel, little endian - a
                          Mot 68k would give a different result). This is exactly what I had expected.

                          Also, you have other problems in your code. I'll post it here again:

                          #include<stdio. h>

                          /* ** You should include other headers here as well, such as */
                          #include <stdlib.h>
                          /* as otherwise exit() is not defined */

                          /* ** You should use int main(void), in C the empty brackets is
                          discouraged and is the old style. Also the meaning between C and C++ is
                          different so portability is lost */
                          int main()
                          {
                          FILE *fp1;
                          int buf[5];
                          int num,i;

                          fp1=fopen("tria ngle.txt","r");
                          if(fp1 == NULL)
                          {
                          printf("file cant be opend");
                          exit(0);
                          }

                          num=fread(buf,s izeof(int),5,fp 1);
                          printf("num of elements read =%d\n",num);

                          /* Instead of 'i<5' you should use 'i<num'. That way your not going to
                          access elements of buf[] that aren't initialised. This is why the last 4
                          values in my output (sizeof int == 4) are also garbage */
                          for(i=0;i<5;i++ )
                          printf("%d\n",b uf[i]);
                          return 0;
                          }

                          Comment

                          • Emmanuel Delahaye

                            #14
                            Re: im facing problem with fread()??

                            Rajshekhar wrote on 24/08/05 :[color=blue]
                            > hi
                            > the file triangle.txt contents are...
                            > 6 6 4[/color]

                            Ok, a text file.
                            [color=blue]
                            > thats it .....
                            > i dont think this file is binary file ..!!![/color]

                            fopen() the file in text mode ("r")

                            You want fgets() to get the line and sscanf() with "%d %d %d" to parse
                            it.

                            --
                            Emmanuel
                            The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
                            The C-library: http://www.dinkumware.com/refxc.html

                            "Clearly your code does not meet the original spec."
                            "You are sentenced to 30 lashes with a wet noodle."
                            -- Jerry Coffin in a.l.c.c++


                            Comment

                            • Suman

                              #15
                              Re: im facing problem with fread()??


                              Jason Curl wrote:[color=blue]
                              > Rajshekhar wrote:[color=green]
                              > > hi
                              > > the file triangle.txt contents are...
                              > > 6 6 4
                              > >
                              > > thats it .....
                              > > i dont think this file is binary file ..!!!
                              > >[/color]
                              >
                              > Rajshekhar, please quote what you're replying to in your message. I for
                              > one can't always see what it is you're replying to, so sometimes your
                              > reply looks like gibberish without context. You'll see this mentioned
                              > often in the newsgroup if you've been reading for some time. It makes it
                              > much more difficult for people to answer you (and decreases the
                              > likelihood that they do)
                              >
                              > Looking at the prototype for fread, it is:
                              >
                              > size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
                              >
                              > Based on your program, it tries to read 5*(sizeof int) from the file.
                              > That's because it doesn't care about spaces, commas or other
                              > punctuation. For that you should look at some other functions such as
                              > fscanf, or write your own parser (much more recommended). There have
                              > been numerous posts to this newsgroup asking the same question you have
                              > in the last month - so please go have a look.
                              >
                              > I don't know what the size of an int is on your machine, but it's
                              > probably 4 or 8.
                              >
                              > From the description I have of 'fread', it says:
                              > "The function fread reads nmemb elements of data, each size bytes
                              > long, from the stream pointed to by stream, storing them at the location
                              > given by ptr."
                              >
                              > This means, if your file has the contents:
                              >
                              > 6 6 4
                              >
                              > This looks like (in binary)
                              >
                              > 0x36 0x20 0x36 0x20 0x34 (values are in hex)
                              >
                              > So, I expect the first value to be something like 0x36203620 or
                              > 0x20362036 depending on the endianness of your machine (one big hex
                              > number, that probably looks random).
                              >
                              > The fact that you're getting a result of zero from fread() might be
                              > because sizeof int is 8 bytes (there aren't 8 bytes in your file
                              > triangle.txt).
                              >
                              > Indeed, when I compile your program, I get the result:
                              > num of elements read =1
                              > 540418102
                              > 134482484
                              > -1075253336
                              > 134513429
                              > 0
                              >
                              > Now ignoring the last 4 digits (because num=1), converting 540418102 to
                              > hex we have exactly 0x20362036 (I'm running an Intel, little endian - a
                              > Mot 68k would give a different result). This is exactly what I had expected.
                              >
                              > Also, you have other problems in your code. I'll post it here again:
                              >
                              > #include<stdio. h>
                              >
                              > /* ** You should include other headers here as well, such as */
                              > #include <stdlib.h>
                              > /* as otherwise exit() is not defined */
                              >
                              > /* ** You should use int main(void), in C the empty brackets is
                              > discouraged and is the old style. Also the meaning between C and C++ is
                              > different so portability is lost */
                              > int main()
                              > {
                              > FILE *fp1;
                              > int buf[5];
                              > int num,i;
                              >
                              > fp1=fopen("tria ngle.txt","r");
                              > if(fp1 == NULL)
                              > {
                              > printf("file cant be opend");
                              > exit(0);
                              > }
                              >
                              > num=fread(buf,s izeof(int),5,fp 1);
                              > printf("num of elements read =%d\n",num);
                              >
                              > /* Instead of 'i<5' you should use 'i<num'. That way your not going to
                              > access elements of buf[] that aren't initialised. This is why the last 4
                              > values in my output (sizeof int == 4) are also garbage */
                              > for(i=0;i<5;i++ )
                              > printf("%d\n",b uf[i]);[/color]

                              ... to say nothing of the missing fclose()![color=blue]
                              > return 0;
                              > }[/color]

                              Comment

                              Working...