Hi.
I want to store the contents of a file into a variable:
You could use:
const char * file_name = "/home/user/foo.txt"
FILE *my_file;
my_file = fopen(file_name, "r");
I suggest you test "my_file" for NULL.
If it is, there was a problem opening the file.
char *file_data;
fscanf(my_file, file_data);
You have declared a pointer, "file_data", but
not assigned it to point to anything.
You are also missing some {input} format
specifiers. See your reference book.
Perhaps you need:
const unsigned int MAX_DATA_SIZE = 256;
char * file_data;
file_data = malloc(MAX_DATA_SIZE);
fscanf(my_file, "%s", file_data);
Or this might work also:
const unsigned int MAX_DATA_SIZE = 1024;
char * file_data;
file_data = malloc(MAX_DATA_SIZE);
fread(file_data, 1, MAX_DATA_SIZE, my_file);
printf("%s\n", file_name);
printf("%s\n", file_data);
Remember:
1. Always check the return values of:
malloc
fopen
fscanf
fread
2. The C language does not have a dynamic string
type. You will have to know how much to allocate
at first, then maybe reallocate again.
3. Pointers, when declared, don't point anywhere
useful. You will have to make them point to
something before you use them.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library