Skip to main content
GameDev.net gamedev.net
🔒 Locked

file loading

Started by unfinished Jan 8, 2004 at 1:48 PM 3 replies 400+ views
Original Post
unfinished
unfinished
i wanted a simple load routine, wrote this is works but am i just being a lameass and missing an easier way. How do i allocate memory large enough for the file at runtime.
void ReadWorld()
{
	int i = 0;
    FILE *input = fopen( "data/world.txt", "r" );
    
    world[i] = getc( input );
    while( world[i] != EOF ) 
	{
	   i++;
	   world[i] = getc( input );
        }
	fclose(input);
//	int a = i;

}
Thanks for anyhelp. Edit: have some source tags . [edited by - Null and Void on January 8, 2004 3:11:04 PM]
Fruny
Fruny

#include <fstream>
#include <vector>
#include <iterator>

std::vector<char> world;

void ReadFile()
{
std::ifstream input( "data/world.txt" );
world.assign( std::istreambuf_iterator(input),
std::istreambuf_iterator() );
}


Or, by hand, in C, allocate a fixed-size buffer, when it is full, allocate a larger one, copy the data, free the first and move on.

Or (brittle), rely on ftell() and fseek().
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Null and Void
Null and Void
Assuming you can seek around in the file and do not want to use anything outside of ANSI C (e.g., stat), this is a relatively simple way to do it:

void ReadWorld(void) {
FILE *input = fopen("data/world.txt", "rt");
long input_size;
void *buffer;

/* Go to the end and ask how far from the beginning we are */
fseek(input, 0, SEEK_END);
input_size = ftell(input);

/* Go back to the beginning */
fseek(input, 0, SEEK_CUR);

/* Allocate a huge buffer to put the file into */
buffer = malloc(input_size);

/* Read it all into buffer */
fread(buffer, 1, input_size, input);

/* Done with the file */
fclose(input);

/* Mess with buffer here... */

/* Done with buffer */
free(buffer);
}

Not tested, but should work if I didn''t typo. No error checking included, you should add it.

SelethD
SelethD
This might help you out. Its how I do files


void RealWord(char *data) //pass in a pointer to hold the data

{
int size;
FILE *input = fopen("data/world.txt","r");

fseek(input,0,2); //seek to end of file

size = ftell(input); //read location of pointer (size of file)

fseek(input,0,0); //move back to top of file


delete data; //make sure not already allocated

data = new char[size];
fread(data,size,1,input); //read in whole file at once


fclose(input);

}


unfinished
unfinished
Thanks for all your help

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.