Weird problem with fwrite() and fread()

This is a discussion on Weird problem with fwrite() and fread() within the C Programming forums, part of the General Programming Boards category; ...actually with fread() only. To begin with, I declared a structure, which consists of five unsigned int numbers. I generate ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    5

    Weird problem with fwrite() and fread()

    ...actually with fread() only.

    To begin with, I declared a structure, which consists of five unsigned int numbers. I generate random numbers for each record, and write the record to a file, using fwrite():

    fwrite(&pent, sizeof(pent), 1, fl);

    I repeat that n times. When all records are in the file, I close the file, and begin a function which reads those records.
    And this is the momment when problem occurs. I read the record using fread():

    fread(&pent, sizeof(pent), 1, fl);

    I also repeat this n times.
    After about (n/10 to n/2) reads, fread starts to return 0, because EOF occured ( I use feof() to check that).
    How is it possible, that EOF occurs so early?! I know that there are n records in the file, so how can it be, that EOF is after (n/10 to n/2) reads?
    Please help me!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,656
    You need to use "wb" in the fopen() call when writing the file, and "rb" when opening the file for reading

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    5
    That did the trick!
    Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 2d array and fwrite and fread
    By totalnewbie in forum C Programming
    Replies: 14
    Last Post: 01-10-2009, 02:45 PM
  2. Replies: 2
    Last Post: 12-26-2008, 03:38 PM
  3. problem with fread and fwrite? bug?
    By moonlord in forum C Programming
    Replies: 17
    Last Post: 08-21-2005, 09:31 AM
  4. buffer type for fread & fwrite
    By daluu in forum C Programming
    Replies: 5
    Last Post: 05-08-2003, 06:57 PM
  5. fread() and fwrite() ?
    By Limblet in forum C Programming
    Replies: 4
    Last Post: 09-25-2001, 07:36 PM

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