it-source

printf () \t옵션

criticalcode 2023. 9. 23. 22:46
반응형

printf () \t옵션

표준 출력에 탭 문자를 인쇄할 때printfC에서, 그것은 길이가 4자로 보이는 약간의 공간을 출력합니다.

printf("\t");

위 케이스에서 탭 너비를 조절할 수 있는 방법이 있습니까?

그건 당신 단말기에 의해 제어되는 것이지, 당신에 의해 제어되는 것은 아닙니다.printf.

printf간단히 a를 보냅니다.\t출력 스트림(atty, 파일 등이 될 수 있음)으로 이동합니다.그것은 많은 공간을 보내지 않습니다.

탭은 탭입니다.공간을 얼마나 많이 사용하는지는 디스플레이 문제이며 셸의 설정에 따라 다릅니다.

데이터의 너비를 제어하려면 의 너비 하위 지정자를 사용할 수 있습니다.printf형식 문자열입니다.예를들면,

printf("%5d", 2);

완전한 솔루션은 아니지만(값이 5자 이상인 경우에는 잘리지 않습니다), 필요에 따라 잘릴 수도 있습니다.

완벽한 제어를 원한다면 아마 직접 구현해야 할 것입니다.

단말기에서 적절한 ANSI 이스케이프 시퀀스를 지원하는 경우 탭 스톱을 화면의 모든 위치에 설정하는 이스케이프 시퀀스가 있습니다.탈출 순서는ESC [ 3 g모든 탭 중지, 이스케이프 시퀀스 지우기ESC H특정 위치에서 탭 중지를 설정합니다.

아래는 지정된 공간 수만큼 탭이 정지하는 기능을 제공하는 POSIX 예제 C 프로그램입니다.먼저 기존 탭을 모두 제거한 다음 공백을 인쇄하고 적절한 위치에 탭 중지를 설정합니다.그런 다음 커서를 줄의 시작 부분으로 되감기 합니다.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>

int writestr(int fd, const char *s) {
    return write(fd, s, strlen(s)) == (ssize_t)strlen(s) ? 0 : -1;
}

int set_tab_stops(unsigned distance) {
    assert(distance > 0);
    // Using stdout here, stderr would be more reliable. 
    FILE *file = stdout;
    const int fd = fileno(file);
    // We have to flush stdout in order to use fileno.
    fflush(file);
    // Get terminal width.
    // https://stackoverflow.com/questions/1022957/getting-terminal-width-in-c
    struct winsize w = {0};
    if (ioctl(fd, TIOCGWINSZ, &w) < 0) return -__LINE__;
    const unsigned cols = w.ws_col;
    // Remove all current tab stops.
    if (writestr(fd, "\033[3g") < 0) return -__LINE__;
    // Do horicontal tabs each distance spaces.
    for (unsigned i = 0; i < cols; ++i) {
        if (i % distance == distance - 1) {
            if (writestr(fd, "\033H") < 0) return -__LINE__;
        }
        if (writestr(fd, " ") < 0) return -__LINE__;
    }
    // Clear the line and return to beginning of the line.
    if (writestr(fd, "\033[1K\033[G") < 0) return -__LINE__;
    return 0;
}

int main() {
    set_tab_stops(10);
    printf("1\t2\t3\t4\n");
    set_tab_stops(5);
    printf("1\t2\t3\t4\n");
}

프로그램 출력과 함께:

1        2         3         4
1   2    3    4

언급URL : https://stackoverflow.com/questions/6646039/printf-t-option

반응형