0

私は C でプログラミングしており、stdin の行数を知る必要があります。一定の行数の後、1 行上にスクロールする必要もあります... ANSI エスケープ コード (033[1S) を使用しましたが、スクロールした行の内容が失われ、これは望ましくありません。

編集: 2 番目のポイントを説明する簡単なコード

#include <stdio.h>

int main(void) { 
    printf("one\ntwo\nthree\n"); 
    fputs("\033[1S", stdout);
return 0; 
}
4

2 に答える 2

1

これは ansi エスケープ コードの良いリファレンスです。コードの表までページを下にスクロールします。

新しい行に移動するには、「1S」に加えて \033[1E が必要になると思います。コードで遊んでください。

また、環境から行/列を取得できると思います。

以下のコードは、 http://www.linuxquestions.org/questions/programming-9/linux-c-syscall-to-get-number-of-columns-of-current-terminal-250252/の「Hko」に感謝します。

#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdio.h>

int main()
{
    struct winsize ws; 

    ioctl(1, TIOCGWINSZ, &ws);
    printf("Columns: %d\tRows: %d\n", ws.ws_col, ws.ws_row);
    return 0;
}
于 2011-01-12T20:13:19.703 に答える
0

stdin とは何かを誤解しているようです。

あなたの例では、コメントのint:

#include <stdio.h> 
int main(void) { 
  int c; int i = 1; 
  printf("one\ntwo\nthree\n"); 
  //while((c=fgetc(stdin)) != NULL) { 
  // comparing it with null is not correct here
  // fgetc returns EOF when it encounters the end of the stream/file
  // which is why an int is returned instead of a char
  while((c=fgetc(stdin)) != EOF) { 
    if (c=='\n') { 
      printf("%d\n", i); i++; 
    } 
  } 
  return 0; 
}

コマンドラインからプログラムを呼び出すと、これが出力されます

$ prog
one
two
three

標準入力を介して情報を提供するには、ストリームまたはパイプを送信する必要があります

$ cat myfile | prog
one
two
three
4 # or however many lines are in myfile

stdin はデフォルトで空白です。入力すると、入力するまで何も送信されません

これは、上記のコードをコンパイルした結果です。

1 ./eof_testing
one
two
three
jfklksdf #my typing here
1
fjklsdflksjdf #mytyping here
2
fjklsdflksdfjf # my typing here
3

----- stty システムコールの追加例 ----

#define STDIN_FD 0
#define STDOUT_FD 1 
#define CHUNK_SIZE 8

#define QUIT_CHAR (char)4 /* C-D */
int main(){
  write(STDOUT_FD,"hi\n",3);
  char buff[CHUNK_SIZE];
  int r, i;
  system("stty -echo raw");
  while(r = read(STDIN_FD, &buff, CHUNK_SIZE)){
    for(i = 0; i < r; i++){
      if(buff[i] == QUIT_CHAR)
        goto exit;
    }
    write(STDOUT_FD, &buff, r);
  }
  exit:
    system("stty echo cooked");
    return 0;
}

ただし、キーが '\r' 文字を送信するため、改行の代わりに行頭に戻るなど、取り組むべきまったく新しい一連の課題があります。これは、文字がプログラムに直接送られるようになったため、端末によって「cooked」モードで発生していた「\n」文字で行が終了しないためです。

http://starboard.firecrow.com/interface_dev/mle.git/editor/editor.c

于 2011-01-13T21:09:03.123 に答える