Free, tested & ready to use examples : c load file memory
AnyExample.com
 
Webanyexample.com
 

How to load file into memory using plain ANSI C language

abstract 
This C language article provides example of loading file (binary mode) into memory for later processing. Only standard libraries (stdio.h) are used.
compatible 
  • Nearly every ANSI C compiler and platform
Here is the function ae_load_file_to_memory, which does:
  • opening file
  • determining its size
  • allocating memory
  • reading file
  • closing file

The first parameter is [pointer to] ASCII string with file name, second -- is pointer to pointer for allocated memory with file contents. Function's Return value is number of readed bytes (file size).

source code: C
#include <stdio.h>
 
int ae_load_file_to_memory(const char *filename, char **result)
{
	int size = 0;
	FILE *f = fopen(filename, "rb");
	if (f == NULL) 
	{
		*result = NULL;
		return -1; // -1 means file opening fail
	}
	fseek(f, 0, SEEK_END);
	size = ftell(f);
	fseek(f, 0, SEEK_SET);
	*result = (char *)malloc(size+1);
	if (size != fread(*result, sizeof(char), size, f))
	{
		free(*result);
		return -2; // -2 means file reading fail
	}
	fclose(f);
	(*result)[size] = 0;
	return size;
}
Here is the test program which uses ae_load_file_to_memory to load file "test.txt" into memory, and print it's bytes in back order:
source code: C
#include <stdio.h>
 
// function ae_load_file_to_memory (see code above) is pasted here 
 
int main() 
{
	char *content; 
	int size;
	size = ae_load_file_to_memory("test.txt", &content);
	if (size < 0) 
	{
		puts("Error loading file");
		return 1;
	}
	do {
		putchar(content[size-1]);
		size--;
	}
	while(size > 0);
	return 0;
}
warning 
  • Function ae_load_file_to_memory returns loaded data size which does not take into account last null-terminate symbol.
  • If you want to use this function to process string data, note that it may work incorrectly with multibyte encodings.
tested by AnyExample.com on 2006-07-19
  • Windows XP :: Microsoft Visual Studio 6.0 / 2003 / 2005
  • FreeBSD 5.2 :: gcc 3.3.3
  • Linux :: gcc 3.4
 


 
© AnyExample 2007
License | Privacy | Contact