在 C 中预填充标准输入 [英] pre-fill stdin in C
问题描述
我的程序应该让用户编辑文件的一行.用户编辑该行并按回车键将其发回.因此,我想打印即将被编辑的当前行,但将其打印在标准输入而不是标准输出上.我不知道如何解决的唯一问题是如何预填充标准输入.我已经试过了:
char cprefill[] = {"您可以编辑此行"};字符 cbuffer[100];fprintf(stdin, cprefill);fgets(cbuffer, 100, stdin);
这似乎是最简单的解决方案,但可能太简单了.fprintf 不会向 stdin 打印任何内容.正确的做法是什么?
这应该是它的样子.请注意可以移动的光标.
首先你需要 libreadline developer 包.(如果您的系统上还没有 libreadline
,您可能还需要它)
在 Debian/Ubuntu 上,apt install libreadline-dev
(加上 libreadline6
如果您还需要二进制文件 - 6
在您的平台)
然后你可以在readline
中添加一个历史记录,就像这样
#include #include #include ...char cprefill[] = {"您可以编辑此行"};添加历史(cprefill);char *buf = readline("行:");printf("编辑的行是 %s\n", buf);//释放readline分配的行免费(缓冲);
用户被提示行:",并且必须执行向上箭头来获取和编辑历史,即cprefill
行.
请注意,您必须使用 -lreadline
readline
打印作为参数给出的提示,然后等待用户交互,允许行编辑,并使用箭头加载存储在历史记录中的行.
然后必须释放 readline
返回的 char *
(因为该函数使用 malloc()
分配缓冲区).>
My program is supposed to let the user edit a line of a file. The user edits the line and sends it back by pressing enter. Therefore I would like to print the current line which is about to be edited, but kind of print it on stdin instead of stdout. The only problem I don't know how to solve is how I can prefill the stdin. I've already tried this:
char cprefill[] = {"You may edit this line"};
char cbuffer[100];
fprintf(stdin, cprefill);
fgets(cbuffer, 100, stdin);
This seems to be the simplest solution, but is probably too simple to work. The fprintf doesn't print anything to stdin. What is the correct way?
Edit:
This is how it is supposed to look like. Please mind the cursor which can be moved.
First you need the libreadline developer package. (You might also need the libreadline
if it's not already available on your system)
On Debian / Ubuntu that's apt install libreadline-dev
(plus libreadline6
if you need the binaries also - 6
might be different on your platform)
Then you can add an history to readline
, like this
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
...
char cprefill[] = {"You may edit this line"};
add_history(cprefill);
char *buf = readline("Line: ");
printf("Edited line is %s\n", buf);
// free the line allocated by readline
free(buf);
User is prompted "Line: ", and has to do UP ARROW to get and edit the history, i.e. the cprefill
line.
Note that you have to compile/link with -lreadline
readline
prints the prompt given as argument, then waits for user interaction, allowing line edition, and arrows to load lines stored in the history.
The char *
returned by readline
has then to be freed (since that function allocates a buffer with malloc()
).
这篇关于在 C 中预填充标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!