在C中将fopen与输入文件名一起使用 [英] Using fopen with input filenames in C

查看:56
本文介绍了在C中将fopen与输入文件名一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码的某个时刻,我想读取将要创建(和/或编辑)的文件的名称,并提出以下建议:

At some point in my code, I want to read a name for a file that I will be creating (and/or editing) and I've come up with the following:

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

即使可以编译并运行,它也不会创建(或打开,如果我手动创建的话)由 filename 指定的文件.
您会提出什么建议?

Even though that does compile and run, it does not create (or open, if I manually create it) the file specified by filename.
What would you suggest?

推荐答案

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

fgets() stores the newline character read from stdin after reading a line of input. You need to strip it manually, e.g.

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

您还应该检查 fopen()是否不返回 NULL ,如果无法打开文件,则会执行此操作.我认为将 fprintf NULL 文件指针一起使用是未定义的行为.

You should also check that fopen() doesn't return NULL, which it will do if it was unable to open the file. I think using fprintf with a NULL file pointer is undefined behaviour.

这篇关于在C中将fopen与输入文件名一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆