我有以下问题:
如何在程序中打印文本,以便对其进行编辑?
例如,程序打印到标准输出:
C:\BlaBlaBlafile.txt
我可以推退格,编辑此文本:
C:\BlaBlaBlafile_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(' ');
}