Thread: Read (BIG) File into char array

  1. #1
    carpe diem
    Join Date
    Jan 2010

    Read (BIG) File into char array

    I have to read a huge data file (~180MB) of unkown size into a char array. I am really not sure how to go about doing this... This is what I have so far:

                   FILE *input; 
                    int count; 
                    char *cFile; 
                    long filelength;          
                    /* file input */ 
                    if ( (input = fopen("inputfile", "rb" )) == NULL) 
                   printf("file not found");
                  // @ checking length of file 
                    fseek(input, 0L, SEEK_END); 
                    filelength = ftell(input);      
                    // read the file into memory 
                    cFile = calloc(filelength + 1, sizeof(char));  //allocate memory for file 
                    if(cFile == NULL) 
                            printf("\nInsufficient memory to read file\n");
               //read file into allocated memory 
                    if (fread(cFile, filelength, 1, input) != 1) 
                            printf("error reading file"); 
    Does anyone have any better suggestions of how to better approach this issue? Right now I don't have the exact file I will be using (180MB of binary data) so I can only test with smaller samples. I am worried once I get the BIG file I won't have sufficient memory=(
    All comments/suggestions appreciated.

  2. #2
    Registered User
    Join Date
    Oct 2008
    Look into the mmap() call as it allows mapping portions of the file into memory.
    This can be of use on systems that don't have enough memory installed in 'em.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Test your system and see how much memory you can allocate dynamically. If you can get enough allocated for your big files, then you don't need to do anything else. Otherwise, design your program to work with only parts of the data, at any one time.

    A little bit of testing and thinking about how you can work with smaller pieces of the data at a time, go a long, long, way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. read from .txt file & put into array?
    By slow brain in forum C Programming
    Replies: 6
    Last Post: 02-25-2003, 05:16 AM