I am trying to open a file to write too but the user needs the ability to select what file they want to open. How do I use fopen to open a string and not a filename?
Printable View
I am trying to open a file to write too but the user needs the ability to select what file they want to open. How do I use fopen to open a string and not a filename?
Just put it in the fopen function...
Code:boolean file(char *filename)
{
FILE *file;
if ((file = fopen(filename, "w")) == NULL) {
return 0;
}
else
{
//code
}
}
thanks
After the first scanf the program is exiting now. Sorry I am new too this.Code:int main()
{
char *input, *output;
FILE *ifp;
printf("Which file would you like to read from?\n");
scanf("%c", &input);
if ((ifp = fopen(input, "r")) == NULL)
{
return 0;
}
printf("Which file would you like to write too?\n");
scanf("%c", &output);
if ((ifp = fopen(output, "w")) == NULL)
{
return 0;
}
return 0;
}
input is a pointer, you need a character array
Code:char filename[_MAX_PATH]; // in MS-Windows this is defined as 255
printf("Which file would you like to read from?\n");
// use fgets() instead of scanf so that you can enter filenames with spaces
fgets(filename,sizeof(filename),stdin);
// now open the file using the above filename.
if ((ifp = fopen(filename, "w")) == NULL)
{
return 0;
}
Don't forget that fgets() leaves a '\n' at the end of the input string. You'll have to chop that off before using it in fopen().