Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Feb 2008
    Location
    Edinburgh - Scotland
    Posts
    107
    Thanks
    0
    Thanked 12 Times in 12 Posts

    Thumbs up C using fread to read an unknown amount of data

    Hey guys.

    I have a text file called test.txt

    Inside it will be a number, it may be as follows:

    1
    2391
    32131231
    3123121412

    I.e it could be any size of number, from 1 digit up to x digits.

    The file will only have 1 thing in it - this number. I want a bit of code using fread which will read that number of bytes from the file and put it into an appropriately sized variable.

    Can anyone suggest the best way to solve this problem?

  • #2
    Supreme Overlord Spookster's Avatar
    Join Date
    May 2002
    Location
    Marion, IA USA
    Posts
    6,280
    Thanks
    4
    Thanked 83 Times in 82 Posts
    Let's see the code you have tried writing to solve this.
    Spookster
    CodingForums Supreme Overlord
    All Hail Spookster

  • #3
    Regular Coder
    Join Date
    Feb 2008
    Location
    Edinburgh - Scotland
    Posts
    107
    Thanks
    0
    Thanked 12 Times in 12 Posts
    Somebody suggested:

    Code:
    char buffer[4096];
    size_t nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp);
    
    if (nbytes == 0)
        ...EOF or other error...
    else
        ...process nbytes of data...
    But this seems wasteful of memory as I am running on an embedded device - so want a more neat solution.

    Another person suggested using fseek to get to the end of the file, then ftell to work out the cursor position which would equal the number of bytes *most of the time* inless the file changes underneath you.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •