[英]Edit text which printed on stdout from stdin in c/c++
我有以下問題:
我如何在程序中打印文本,以便我可以編輯它?
例如,程序打印到stdout:
C:\\BlaBlaBla\file.txt
我可以按退格鍵,編輯此文本:
C:\\BlaBlaBla\file_1.txt
我會很高興任何信息。
獲取命令行編輯的一種方法是使用GNU readline庫提供的功能。
我使用malloc以這種方式解決了這個問題(使用退格,刪除和箭頭(左和右)):
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <malloc.h>
#define ENTER 13
#define ARROW 224
#define LEFT 75
#define RIGHT 77
#define SEPARATOR 219
#define DELETE 83
#define BACKSPACE 8
void editText(char *s);
void printTextWithCursor(char *s, size_t position);
int insertInStr(char **s, size_t position, char c);
void deleteSymbol(char *s, size_t position);
#define TEXT "Some text."
int main()
{
unsigned char c;
char *s = malloc(strlen(TEXT)+1);
__int64 pos;
strcpy(s, TEXT);
pos = strlen(s);
printf("The original text:"TEXT"\n");
printf(TEXT"%c", SEPARATOR);
while((c = getch())!= ENTER)
{
putchar('\r');
switch(c)
{
case ARROW://OR DELETE
c = getch();
if (c == LEFT && pos > 0)
pos--;
if (c == RIGHT && pos < strlen(s))
pos++;
if(c == DELETE && pos < strlen(s))
deleteSymbol(s, pos);
break;
case BACKSPACE:
if(pos > 0)
deleteSymbol(s, --pos);
break;
default:
if(pos >= 0 && pos <= strlen(s))
{
insertInStr(&s, pos++, c);
}
}
printTextWithCursor(s, pos);
}
return 0;
}
void deleteSymbol(char *s, size_t position)
{
size_t i, len = strlen(s);
for(i = position; i < len; i++)
s[i] = s[i+1];
}
int insertInStr(char **s, size_t position, char c)
{
__int64 i;
if((*s = realloc(*s, strlen(*s) +1 +1)) == 0)
return 0;
for(i = strlen(*s)+1; i >= position; i--)
(*s)[i] = i == position ? c : (*s)[i-1];
return 1;
}
void printTextWithCursor(char *s, size_t position)
{
size_t currPos, length = strlen(s);;
for(currPos = 0; currPos <= length; currPos++)
{
putchar(currPos < position ? s[currPos] : currPos == position ? SEPARATOR : s[currPos-1]);
}
putchar('\0');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.