加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在屏幕上打印和文本文件

发布时间:2020-12-16 10:38:14 所属栏目:百科 来源:网络整理
导读:我需要将某些内容转储到文本文件中,同样需要在屏幕上显示. (我说的是C程序的实用程序) 菜单选项如下所示, 1. display AA parameters2. display BB parameters3. display CC parameters4. dump all5. ExitSelect option 如果他们选择1/2/3,它只需要在屏幕上显
我需要将某些内容转储到文本文件中,同样需要在屏幕上显示. (我说的是C程序的实用程序)
菜单选项如下所示,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

如果他们选择1/2/3,它只需要在屏幕上显示,或者如果他们选择选项#4,它需要逐个显示所有参数,同样需要转储到.txt文件中.

我知道,我们可以使用printf和fprintf函数在屏幕上显示并分别将其写入文本文件.问题是我显示了20多个参数,每个参数至少有20个子参数.

我目前正在实施如下,

printf (        "Starting serial number       [%ld]n",serial_info_p->start_int_idx);
fprintf(file_p,"Starting serial number       [%ld]n",serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]n",serial_info_p->current_int_idx);
fprintf(file_p,"Current Serial number         [%d]n",serial_info_p->current_int_idx);

有没有最简单的方法来实现这一点来减少代码行数?

解决方法

到目前为止,我会比人们的建议更激进,但也许对你来说太过分了. (‘inline’关键字是C99;如果编码为C89,则可以省略它而没有太大后果.)

/*
** These could be omitted - unless you get still more radical and create
** the format strings at run-time,so you can adapt the %-24s to the
** longest tag you actually have.  Plus,with the strings all here,when
** you change the length from 24 to 30,you are less likely to overlook one!
*/
static const char fmt_int[]  = "%-24s [%d]n";
static const char fmt_long[] = "%-24s [%ld]n";
static const char fmt_str[]  = "%-24s [%s]n";   /* Plausible extra ... */

static inline void print_long(FILE *fp,const char *tag,long value)
{
    fprintf(fp,fmt_long,tag,value);
}

static inline void print_int(FILE *fp,int value)
{
    fprintf(fp,fmt_int,value);
}

static inline void print_str(FILE *fp,const char *value)
{
    fprintf(fp,fmt_str,value);
}

static void dump_data(FILE *fp,const serial_info_t *info)
{
    dump_long("Starting serial number",info->start_int_idx);
    dump_int( "Current Serial number",info->current_int_idx);
    /* ... and similar ... */
}

然后调用代码将为选项4调用dump_data()一次(使用参数stdout)选项1,2,3和两次(一次使用stdout,一次使用输出文件的文件指针).

如果参数的数量真的很大(达到数百个),我甚至会考虑一个编码类型和偏移信息的数据结构(偏离< stddef.h>)和指向函数等的指针.比如,所以dump_data()中只有一个循环迭代一个编码所有必要信息的结构.

您还可以通过对数据结构的所有整数成员使用相同的基本整数类型(在您的示例中为long)来简化生命.

弗雷德布鲁克斯在“神话人月”中 – 如果你还没有这本书,那么这本书值得一读,但请确保你阅读了二十周年纪念版 – 在第9章中说:

Show me your flowcharts [code] and conceal your tables [data structures],and I shall continue to be mystified. Show me your tables,and I won’t usually need your flowcharts; they’ll be obvious.

这个代码的表驱动版本最终可以节省空间,并且当必须以相同方式更改一百个相关函数时会感到沮丧,而表格数据中的简单更改可以修复整个批次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读