How to store the contents of a file into a variable

F

francescomoi

Hi.

I want to store the contents of a file into a variable:
------------
char file_name[] = "/home/user/foo.txt";
FILE *my_file;
my_file = fopen(file_name, "r");

char *file_data;
fscanf(my_file, file_data);

printf("%s\n", file_name);
printf("%s\n", file_data);
 
E

Eric Sosman

Hi.

I want to store the contents of a file into a variable:
------------
char file_name[] = "/home/user/foo.txt";
FILE *my_file;
my_file = fopen(file_name, "r");

char *file_data;
fscanf(my_file, file_data);

printf("%s\n", file_name);
printf("%s\n", file_data);

Several things. One mistake is covered by Question 7.1
(see also Questions 7.2 and 7.3) in the comp.lang.c Frequently
Asked Questions list

http://www.eskimo.com/~scs/C-faq/top.html

Another of your mistakes doesn't seem to be covered in
the FAQ. Point to ponder: Where is the "scan pattern" or
"scan format" in your fscanf() call?
 
T

Thomas Matthews

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top