opening a file based on a variable.

L

Levi Campbell

I have a function that as one of its arguments is a variable for a file
name, how would I use the variable to fill in the file name when
calling fopen?
 
B

Ben Pfaff

Levi Campbell said:
I have a function that as one of its arguments is a variable for a file
name, how would I use the variable to fill in the file name when
calling fopen?

void
function (const char *filename)
{
FILE *file = fopen (filename, "r" /* etc. */);
if (file != NULL) {
/* ...use file... */
}
}
 
P

Peter Nilsson

Levi said:
I have a function that as one of its arguments is a variable for a
file name, how would I use the variable to fill in the file name
when calling fopen?

Exactly the same way you'd use a string literal for a fixed file
name.

If you have actual code that is failing, I suggest you post it
because your problem probably has nothing to do with fopen per se.
 
K

Keith Thompson

Levi Campbell said:
I have a function that as one of its arguments is a variable for a file
name, how would I use the variable to fill in the file name when
calling fopen?

By calling fopen() with the argument.
 
M

Martin Ambuhl

Levi said:
I have a function that as one of its arguments is a variable for a file
name, how would I use the variable to fill in the file name when
calling fopen?

As you would use a string as an argument to any other function taking a
string as an argument. For example,

#include <stdio.h>
int main(void)
{
FILE *fp;
char foobar[] = "random.filename.txt";
if (!(fp = fopen(foobar,"r")))
{
fprintf(stderr,"Oh crap! I couldn't open \"%s\" for input.\n",
foobar);
}
else fclose(fp);
return 0;
}
 

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

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,459
Latest member
Vida00R129

Latest Threads

Top