在 C 中将 fopen 与输入文件名一起使用

Using fopen with input filenames in C

在我的代码中的某个时刻,我想读取我将要创建的文件的名称(and/or 编辑),我想出了以下内容:

FILE *fp;
char filename[15];
fgets(filename, 15, stdin);
fp = fopen(filename, "a");
fprintf(fp, "some stuff goes here");
fclose(fp);

即使它编译并且 运行,它也不会创建(或打开,如果我手动创建它)由 filename 指定的文件。
你有什么建议?

您需要声明 filename[16] 才能使用 15 个字符,您需要 space 作为终止零。

fgets()存储读取一行输入后从stdin读取的换行符。您需要手动剥离它,例如

size_t len = strlen(filename);
if (len > 0 && filename[len - 1] == '\n')
    filename[len - 1] = '[=10=]';

您还应检查 fopen() 是否 return NULL,如果它无法打开文件,它会这样做。我认为将 fprintfNULL 文件指针一起使用是未定义的行为。

通常(但不总是),fgets() 会给你一个额外的 '\n' 追加输入的字符串,因为

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

参考:http://www.cplusplus.com/reference/cstdio/fgets/

要使用最少的代码摆脱 '\n'

fgets(filename, 15, stdin);
filename[strcspn(filename, "\n")] = '[=10=]';

因为 fgets 将读取字符串 util 一个 EOF 或一个换行符,如果读取了一个换行符,它将被存储到缓冲区中。这意味着您必须手动 trim 结束换行符(如果有)。我建议改用 fscanf,它不会将换行符添加到缓冲区:

char filename[15];
int ret = fscanf(stdin, "%s", filename);
if (ret != 1) { // handle input error }
fp = fopen(filename, "a");