【问题标题】:printf the contents of a file (documentation) at compile timeprintf 编译时文件(文档)的内容
【发布时间】:2021-09-13 16:02:44
【问题描述】:

为 hacky 程序打印文档的多产方式通常是:

void print_help(){
    printf("a whole bunch of information
            generally spanning many lines and looking ugly
            requires editing a c file to modify documentation");
}

这是丑陋的 IMO,并且不容易修改文档。替代方案:

一般不屑一顾:

void print_help(){
    printf("read the README, you idiot");
}

容易出错,复杂:

void print_help(){
    fopen("readme.md", "r");
    //error check;
    while (read from file){
         printf("%s", line);
    }
}

我想弥补解决方案 1 和 3 之间的差距,即:

void print_help(){
    printf("#include"help_file.txt"");
}

我想我的问题是:

  • 真的这么简单吗?预处理器会跳过字符串,还是会注意到包含指令?
  • 潜在问题?我知道任何不能很好地 printf 的东西如果放在文件中都会导致问题

【问题讨论】:

  • 你试过编译吗?是的,你可以这样做这样,但不能像你那样做。
  • 预处理器指令必须位于行首(空格除外)。而且它们不会在字符串中处理。
  • @EugeneSh。我确实尝试过,但转义序列的任何排列都失败了。一个人会如何做这样的事情like?整个 printf 是否必须在文本文件中?
  • @KamilCuk 你没看错,但似乎最好的答案仍然在这个问题中

标签: c c-preprocessor


【解决方案1】:

创建一个将文档定义为变量的包含文件。

help_file.h:

char *help_text = "
a whole bunch of information\n\
generally spanning many lines and looking ugly\n\
requires editing a c file to modify documentation"

program.c:

void print_help(){
    #include "help_file.h"
    printf("%s", help_text);
}

您可以使用 shell 脚本从普通的 .txt 文件创建包含文件。

【讨论】:

  • 使用纯文本文件一定有什么技巧..虽然想不出一个
  • 不,我想不到。
  • 是的,可能只有一些额外的脚本
【解决方案2】:

预处理器不处理字符串的内容,因此不能用这样的字符串替换文件的内容。

如果您希望帮助文件是看起来不像一系列 C 字符串的纯文本,您唯一的选择是在运行时读取外部文件的内容并打印它。而且我不会完全称它为容易出错或复杂的:

void print_help()
{
    FILE *f = fopen("readme.md", "r");
    if (!f) {
        printf("can't print help file");
    } else {
        char line[500];
        while (fgets(line, sizeof line, f){
          puts(line);
        }
        fclose(f);
    }
}

【讨论】:

  • 容易出错的原因是为fopen("readme.md", "r");的第一个参数找到可靠的文件路径
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多