Thread: How to read a file in chunks

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    How to read a file in chunks

    Good day,

    I'd like to read a file, 15 characters at a time, until the end of the file. Can someone tell me what functions should I use? Thanks.

  2. #2
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    Just use fgets

    Code:
    FILE *fp;
    char buff[15];
    
    fp=fopen("abc.txt","r");
    
     while ((fgets(buff,sizeof(buff),fp)) != NULL)
     {
         /*process the chunk here */
     }
    Ofcourse, do all the error checking for pointer fp before using it.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    204
    So on the next call of fgets() it will continue from where it stopped?

  4. #4
    Climber spoon_'s Avatar
    Join Date
    Jun 2002
    Location
    ATL
    Posts
    182
    Quote Originally Posted by caduardo21
    So on the next call of fgets() it will continue from where it stopped?
    Yes, the file pointer keeps track of that stuff.

    Look up the function fseek, maybe it will make more sense to you then.
    {RTFM, KISS}

  5. #5
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Whoa, you don't want to use fgets() to read 15 bytes at a time. Look up the the function fread() instead. fgets() will stop reading whenever it hits a newline. Not to mention that passing 15 as the 2nd parameter to fgets() will actually only read 14 bytes since it leaves room for a \0.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File Writing Problem
    By polskash in forum C Programming
    Replies: 3
    Last Post: 02-13-2009, 10:47 AM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. Hmm....help me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 AM