> From: "Frank" <f_******@prodigy.net>
Could someone tell me how to open a file at run time
You were already doing that, but didn't realize it.
that I didn't know the name of at compile time?
I'll get to that later.
I know how to open a file at compile time ...
No you don't. You are quite confused!
If the file were opened at compile time, then if you compile the
program then replace the data file with a new version the compiled
program would still be using the old data from before the program was
compiled instead of the new data you put in the file later. Think about
it.
... fopen("shoppinglist.txt", "r") ...
That does *not* open the file at compile time! Here's what happens:
You specify the file name as a string literal at compile time.
At that time the file doesn't even have to exist yet.
The string literal is compiled into the program, and written into
object file, and later passed to the loader.
The fopen call is compiled, with pointer to that string literal,
written into object file, and later passed to loader too.
(The object file might be virtual, or deleted shortly, so you might
never really see it.)
The loader reads in the object file and builds the runnable. Even now
the data file doesn't yet have to exist.
When you try to run the program, i.e. you invoke the runnable, the code
for the literal and the code for the fopen call are brought into
memory, then the pointer to the literal is put in a register or on the
stack and control is passed to fopen. Even now the file doesn't have to
yet exist, but suddenly the innerds of fopen look for the file and
*now* the file must exist and *now* the file is finally being opened.
Suppose you create a data file by some other name, don't rename it
to the correct name yet. Also, you put a sleep for five seconds
in the program just before the fopen. Something like this:
printf("Sleeping...\n");
...code to sleep...
printf("done, going ahead with fopen...\n");
...fopen...
Now when you run that program you wait until it says Sleeping.., and
*then* you quickly rename the file to have the correct name, and the
program works fine.
Another experiment: Have correct name, but while program is
sleeping you rename file to have wrong name. Now program bombs out
due to not finding the file where it's supposed to be.
These experimetns prove the file isn't opened until runtime after the
sleeping is finished. It isn't even opened at the time the runnable is
started! Not until later when execution reaches the point in sequence
where the fopen is called.
This differs from FORTRAN IV an old IBM 360/370 batch system where all
files are opened at the time the program is started, before any
executable statements in the program have been run! Do you remember way
back then?
Back to your question: Don't use a string literal, use a char* pointer
or char[...] array that you fill with characters of filename just
before you call fopen.