im getting the fopen() is a directory and I am unable to locate my error,
it works perfectly with put and fgets. (Code That Works)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) // Use a valid prototype for main
{
char path[256] = "/your/fixed/path/";
size_t len = strlen(path);
puts("Enter a file name:");
// Get the file name leaving room for the path
if (fgets(path len, sizeof(path) - len, stdin))
{
// Strip the trailing new line
path[strcspn(path, "\n")] = 0;
}
// Nothing to concat
FILE *file = fopen(path, "w");
// Always check the result of fopen
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
// Do your stuff ...
fclose(file);
return 0;
}
I want to use printf and scanf instead of puts and fgets, and when I use the below code I get the reply as fopen() is a directory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) // Use a valid prototype for main
{
char path[256] = "./casestudy/";
size_t len = strlen(path);
char *bt ="dd.txt";
// Get the file name leaving room for the path
if(path len, sizeof(path) - len, bt)
{
// Strip the trailing new line
path[strcspn(path, "\n")] = 0;
}
// Nothing to concat
FILE *file = fopen(path, "w");
// Always check the result of fopen
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
// Do your stuff ...
fclose(file);
return 0;
}
CodePudding user response:
You probably want something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) // using valid prototype for main
{
char path[256] = "./casestudy/";
puts("Enter the filename: ");
// Ask for filename from the user
char filename[256];
fgets(filename, sizeof(filename), stdin);
filename[strcspn(path, "\n")] = 0; // remove trailing \n if any
// concatenate user provided filename to the path
strcat(path, filename);
// now path contains the full path to the file
printf("Full path is \"%s\".", path);
// FILE *f = fopen(path, ....)
// ...
}
Disclaimer: there is no checking for valid input, if the user provides a filename which is too long you'll get a buffer overflow. I let you deal with this as an exercise.