Reputation: 29
Suppose I have two methods: int main(void)
and void func(char *FileName)
.
The main
method will scan in, the name of a file from a user then save the value to char fileInput[20]
, then call func(fileInput)
.
In the func
method, I want to open a file FILE *infile = fopen(/*FileName as string value*/, "rb");
, but using the parameter value as the file name to be opened.
void func(char *FileName){
//Open the file.
//FileName = address of first element of char array
//*FileName = value of first element of char array
//But How can I use the all the elements of the char array as a string ?
FILE *infile = fopen(/*FileName as string value*/, "rb");
}
int main(void) {
//Assuming the user will always enter a valid value.
char fileInput[20];
//Prompt the user to input a value.
printf("File name then enter: ");
//Save the input value to fileInput.
scanf("%s", fileInput);
func(fileInput);
}
As an example, if the fileInput[20] = "hello";
, then call the func(fileInput);
How can i open a file in the func
method using the "hello"
value?
FILE *infile = fopen(value of fileInput = "hello", "rb");
Upvotes: 0
Views: 364
Reputation: 1702
I am not sure if this is what you are asking but, this is the function prototytpe of fopen()
,
FILE *fopen(const char *pathname, const char *mode);
pathname
is a pointer to char. You are not limited to hard-coding the pathname
, you can provide a variable to it (assuming its of type char *
).
So this:
FILE *infile = fopen(/*FileName as string value*/, "rb");
Becomes this:
FILE *infile = fopen(FileName, "rb"); /* Filename is the argument you provided by calling the function */
Upvotes: 1