我正在尝试使用 fopen 打开一个文件,但我不想要一个静态位置,所以当他/她运行程序时我从用户那里获取字符串。但是,如果用户不输入,则指定默认文件。
我可以将 malloc var 放入 fopen 路径参数中吗?
char *file_path_mem = malloc(sizeof(char));
if (file_path_mem != NULL) //Null if out of memory
{
printf("Enter path to file, if in current directory then specify name\n");
printf("File(default: marks.txt): ");
while ((c = (char)getchar()) != '\n')
{
file_path_mem[i++] = c;
file_path_mem = realloc(file_path_mem, i+1 * sizeof(char));
}
file_path_mem[i] = '\0';
if (i == 0 && c == '\n')
{
file_path_mem = realloc(file_path_mem, 10 * sizeof(char);
file_path_mem = "marks.txt";
}
}
else
{
printf("Error: Your system is out of memory, please correct this");
return 0;
}
if (i==0)
{
FILE *marks_file = fopen("marks.txt", "r");
}
else
{
FILE *marks_file = fopen(file_path_mem, "r");
}
free(file_path_mem);
正如您可能已经猜到的那样,我是新手,所以如果我做错了可怕的事情,那么对不起。