473,587 Members | 2,505 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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("shopping list.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 3642
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("shopping list.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**********@i nvalid.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.ne t
Nov 15 '05 #4
> From: "Frank" <f_******@prodi gy.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("shopping list.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("Sleepin g...\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
12144
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 files at java.lang.UNIXProcess.forkAndExec(Native Method) at java.lang.UNIXProcess.<init>(UNIXProcess.java:54) at...
9
13409
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. But the open() on ifstream only takes char * strings (mbcs?). In old iostreams, I could _wopen() the file, get the filedesc, and call attach() on...
3
1855
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
2470
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 access this .mdb. My .aspx pages are using OleDb for the data retrieval. I do not want those runtime errors. Please enlighten me as to how to get rid...
0
2553
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 datalist. When the next user selects trys to run the page, the page fails and I get a generic error message from the stack trace. I am assuming...
2
4226
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: ---------------------------------------------------------- Exception from HRESULT: 0xC004800A Description: An unhandled exception occurred during the execution...
6
34633
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 I would ignore processing that particular file and move to next file. How can I check whether the file is open or not? I tried os.stat and...
0
1352
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 web page which contains a help page.
8
7457
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 runtime...and to make matters worse users are allowed to use images in any format...so long as they have the filename that matches the property name. My...
0
7849
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8215
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8347
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7973
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6626
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3844
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2358
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1189
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.