printf 编译时文件(文档)的内容
printf the contents of a file (documentation) at compile time
为 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"");
}
我想我的问题是:
- 真的这么简单吗?预处理器会跳过字符串,还是会注意到 include 指令?
- 潜在问题?我知道任何不能很好地 printf 的东西如果放在文件中都会引起问题
创建一个将文档定义为变量的包含文件。
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
文件创建包含文件。
预处理器不处理字符串的内容,因此您不能用这样的字符串替换文件的内容。
如果您希望帮助文件是看起来不像一系列 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);
}
}
为 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"");
}
我想我的问题是:
- 真的这么简单吗?预处理器会跳过字符串,还是会注意到 include 指令?
- 潜在问题?我知道任何不能很好地 printf 的东西如果放在文件中都会引起问题
创建一个将文档定义为变量的包含文件。
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
文件创建包含文件。
预处理器不处理字符串的内容,因此您不能用这样的字符串替换文件的内容。
如果您希望帮助文件是看起来不像一系列 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);
}
}