我想用fopen打开一个文件,但我不想要一个静态位置,所以我在用户运行程序时从中获取字符串。 但是,如果用户没有输入,则指定默认文件。在malloc中打开一个带有路径的文件
我可以将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新手,所以如果我做了一些可怕的错误,那么对不起。
that和realloc可能会失败 – Bahbar 2009-11-19 22:00:48
所以malloc可以介意。每次1步:) – Goz 2009-11-19 22:05:56
“分配很慢”。诚然,I/O也是如此。 – 2009-11-19 22:16:09