473,385 Members | 1,925 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Open a file at runtime

Could someone tell me how to open a file at run time
that I didn't know the name of at compile time?
I know how to open a file at compile time when I know
what the name is going to be.

FILE *p_afile;

if((p_afile = fopen("shoppinglist.txt", "r")) == NULL)
{
fprint("Could not open file");
}

However, lets say I ask the user what file he wants
to open and he types in a name like NFLteams. I put
that name into maybe a char type variable then
what is the syntax to open it?
Nov 14 '05 #1
4 3615
Frank wrote:
Could someone tell me how to open a file at run time
that I didn't know the name of at compile time?
I know how to open a file at compile time when I know
what the name is going to be.

FILE *p_afile;

if((p_afile = fopen("shoppinglist.txt", "r")) == NULL)
{
fprint("Could not open file");
fprint is no standard C function; you probably mean
printf(....) or fprintf(stderr,....);
}

However, lets say I ask the user what file he wants
to open and he types in a name like NFLteams. I put
that name into maybe a char type variable then
what is the syntax to open it?


Let's look at the prototype of fopen():

FILE *fopen (const char *filename, const char *mode);

So, you need your file name at runtime in an object
that fits the description of filename. This can be
a string literal (as above) or an array of char
containing a C string or a char * pointing to a C
string; however it cannot be a "char type variable",
as this gives no C string but a single char.

So, we could have
#define NAMELEN 80
.....
char buf[NAMELEN+1];
....
/* get filename of length <= NAMELEN from user and store it in buf */
....
p_afile = fopen(buf, "r");
if (p_afile == NULL) {
....

or
int main (int argc, char **argv)
{
char *filename;
....
if (argc <= 1)
filename = "default"; /* Note: we are _not_ copying
"default" anywhere but let filename
point at the start of default. */
else
filename = argv[1];
....
p_afile = fopen(filename, "r");
....
}
or
char *filename;
....
/* allocate storage for filename and read file name into filename */
....
p_afile = fopen(filename, "r");
....

For how to read in user input, have a look at the comp.lang.c FAQ
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
> > fprint("Could not open file");

fprint is no standard C function; you probably mean
printf(....) or fprintf(stderr,....);

Yes, Michael you are correct; I wanted to type "fprintf(" but the hour
being late and my fingers needing sleep seemed to have resulted in
not hitting the 'f' key hard enough.
Thanks for answering my question of how to handle an unknown
file name at compile time. The one dimensional char array variable
is something I can understand and I am going to type it into my
compiler right now and see what happens.
Frank
Nov 14 '05 #3
On Fri, 17 Jun 2005 07:07:12 +0200, Michael Mair
<Mi**********@invalid.invalid> wrote:

<snip>
char buf[NAMELEN+1];
....
/* get filename of length <= NAMELEN from user and store it in buf */
....
p_afile = fopen(buf, "r");
if (p_afile == NULL) {
....


And to forestall the OP's next question(s):

Don't use gets() to read the filename into buf, at least not if anyone
else will ever give input to your program: they can make it overrun
your buffer and at minimum crash your program; on many systems
depending on their skill they can do much more extensive damage.

fgets() prevents this (if used sanely) but unlike gets() it includes
in the value stored the newline ending the input line if not overlong.
You almost certainly don't want that newline in your filename -- on
some systems it is flat illegal, and on others a Very Very Bad Idea.
So check for it and remove it before using buf for the fopen() call.

- David.Thompson1 at worldnet.att.net
Nov 15 '05 #4
> 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.
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Gert Schumann | last post by:
I'm operating on sun OS 5.6 I ping a host every 10 seconds to get knowlegde wheather it is running or not. After about one and a half hour I get this Exception: java.io.IOException: Too many open...
9
by: Charles F McDevitt | last post by:
I'm trying to upgrade some old code that used old iostreams. At one place in the code, I have a path/filename in a wchar_t string (unicode utf-16). I need to open an ifstream to that file. ...
3
by: red | last post by:
I have this: using System; using System.Runtime.InteropServices; using System.Text; class FileReader { const uint GENERIC_READ = 0x80000000; const uint OPEN_EXISTING = 3;
2
by: Gayathri | last post by:
Hi I am using MS Access to store the data in an .mdb file. And I observe that, if the .mdb is open, I receive a runtime error whenever I/someone tries to access any of the .aspx pages that needs to...
0
by: troutbum | last post by:
I am experiencing problems when one user has a document open through a share pointing to the web site. I use the dsolefile to read the contents of a particular directory and then display them in a...
2
by: Seok Bee | last post by:
Dear Experts, In my web application, I am having a button to open a file located in the server. When I click on the button to view the file, I received the following error message:...
6
by: Ros | last post by:
There are 10 files in the folder. I wish to process all the files one by one. But if the files are open or some processing is going on them then I do not want to disturb that process. In that case...
0
by: Guern1 | last post by:
Hi Sorry if I have posted this to the wrong forum. Need a bit of help here please to point me in the right direction. I have a java class file here which i wish from a menu item to open a...
8
by: Ron | last post by:
I am building a dynamic image loading class. I have a list of properties that have associated images in a specified directory. The problem they are multiple formats which are not known at...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.