在C++中使用 Linux 的控制台大小

Console size using Linux in C++

本文关键字:控制台 Linux C++      更新时间:2023-10-16

我正在尝试创建一个像 Linux more这样的程序,而无需一些参数。主要思想是我需要从命令字符串中带有一些参数的文本文件输出信息。所以我的主要论点是more -d fileName.

我知道more输出 23 个带有文本的字符串,第 24 个是用户按 space 并获得另一个信息屏幕,但我需要考虑用户可以更改控制台窗口的大小。

我正在尝试使用库#include <sys/ioctl.h>,但它说我不能使用这样的库。 我做错了什么?

我的代码:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sys/ioctl.h>
void printRecord(struct winsize w, std::vector<std::string> lines);
int main(int argc, char *argv[]) {
    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    std::ifstream readRecord;
    std::string more("more");
    std::vector<std::string> lines;
    std::cout << "argc: " << argc << std::endl;
    for (int i = 0; i < argc; i++)
    {
        std::cout << "Argument: " << i << " = " << argv[i] << std::endl;
    }
    std::cout << std::endl << std::endl;
    if (argv[1] == more)
    {
        std::string str;
        //int n = atoi(argv[2]);
        int numberPages=0;
        readRecord.open(argv[2]);
        while (!readRecord.eof())
        {
            getline(readRecord, str);
            numberPages++;
            lines.push_back(str);
        }
        if (0 == numberPages)
        {
            std::cout << "ERROR: The file is empty" << std::endl;
            exit(-1);
        }
        if (w.ws_row > numberPages)
        {
            printRecord(struct winsize w, lines);
        }
        else
        {
            printRecord(struct winsize w, lines);
        }
    }
    return 0;
}
void printRecord(struct winsize w,std::vector<std::string> lines)
{
    for (int i = 0; i < w.winsize::ws_row; i++)
    {
        std::cout << lines[i] << std::endl;
    }
}

错误:

Source.cpp: In function ‘int main(int, char**)’:
Source.cpp:12:11: error: ‘STDOUT_FILENO’ was not declared in this scope
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
Source.cpp:44:16: error: expected primary-expression before ‘struct’
printRecord(struct winsize w, lines);
Source.cpp:48:16: error: expected primary-expression before ‘struct’
printRecord(struct winsize w, lines);

问题是你用了

#include <sys/ioct1.h>

还有一个错别字:1 而不是 L。尝试:

#include <sys/ioctl.h>

相反