gpt4 book ai didi

c - 在 malloc 中打开带有路径的文件

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:44 25 4
gpt4 key购买 nike

我试图用 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);

你可能已经猜到我是一个 c 新手,所以如果我做错了什么可怕的事情,那么抱歉。

最佳答案

这不是你想的那样:

file_path_mem = realloc(file_path_mem, 10 * sizeof(char);
file_path_mem = "marks.txt";

您要做的是更改第二行以将默认名称复制到分配的缓冲区中:

strcpy(file_path_mem, "marks.txt");

关于c - 在 malloc 中打开带有路径的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1766790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com