使用用户给定名称打开文件(c 中的 fopen)

opening a file with a user given name (fopen in c)

我需要从用户那里获取用户名并打开一个包含他的名字的文件(如果该文件已经存在)。 如果该文件不存在,我需要创建一个。 现在我真的不知道该怎么做。 (c)

此代码行合法吗?

fopen("%s.txt", "r+", username);

如果没有,我有什么选择? 也许有更好的方法?

感谢您的帮助:)

你有正确的想法,但没有使用正确的功能去做。

char *filename = malloc(strlen(username) + strlen(".txt")+1);

if (filename) {
  sprintf(filename, "%s.txt", username);
  fopen(filename, "r+");
}

试试这个:

char* ext = ".txt";
char* filename = malloc(strlen(username) + strlen(ext) + 1);
sprintf(filename, "%s%s", username, ext);
FILE* file = fopen(filename, "r+");
free(filename);