im new to C, im trying to save a file created in the c program beginner.c in a directory called casetudy. How can I implement that as fileopen() funtion only accepts 2 arguments. The FILE_NAME also dynamically changes, how can I do both accept dynamically changing files names and a fixed directory path?
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define FILE_NAME "tex.txt"
int main(){
FILE* file_ptr = fopen(FILE_NAME, "w");
fclose(file_ptr);
}
CodePudding user response:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// #include <unistd.h> you don't need this
#define FILE_NAME "tex.txt"
int main(void) // Use a valid prototype for main
{
char path[256] = {0}; // Buffer for dynamic path
puts("Enter a path:");
// Get the path leaving room for FILE_NAME
if (fgets(path, sizeof(path) - strlen(FILE_NAME), stdin))
{
// Strip the trailing new line
path[strcspn(path, "\n")] = 0;
}
// Concat FILE_NAME
strcat(path, FILE_NAME);
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;
}
what is its the other way round the path is fixed the filename is dynamic?
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");
...