c++ - 在 C++ 程序中执行行计数 bash 命令(wc -l)

标签 c++ bash shell

<分区>

我想在声明一个全局数组之前计算数据文件的行数。我知道在终端中,如果我执行 wc -l filename,我会得到行数。我如何使用该命令 (wc -l filename) 并将其结果存储到 C++ 程序中的 int 类型变量中?当我使用以下代码时: int NT=system("wc -l file.d"); 我得到 NT=0.

如何获得号码。 NT 中 file.d 中的行数?

最佳答案

什么应该是一个相当有效的解决方案,尽管它不能在 POSIX 系统之外移植(阅读:您必须重写以在 Windows 上使用 WinAPI 等效调用),因为它避免了实际构造对象、执行显式读取的需要对于每一行,等等。除了 mmap 工作(其中大部分至少可以被分解),它基本上是一个单行。

我一般不推荐这样做(你的问题应该通过使用 std::vector 或类似的东西来解决,这样你的数据结构就可以动态增长以匹配行数),但如果你好奇的话,我会把它放在这里。

#include <algorithm>

#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const char* map_whole_file(const char *filename, size_t& map_size);

int main(...) {
    const char *filename = ...;  // From argv, constant, whatever
    size_t map_size;

    const char *data = map_whole_file(filename, map_size);

    // Number of lines is count of newline characters, +1 if final line not
    // terminated with newline
    size_t numlines = std::count(data, data+map_size, '\n') + (data[map_size-1] != '\n');

    munmap(data, map_size);
}

const char* map_whole_file(const char *filename, size_t& map_size) {
    int fd = open(filename, O_RDONLY);
    if (fd == -1)
        ...handle_error...;

    struct stat sb;
    if (fstat(fd, &sb) == -1)           /* To obtain file size */
        ...handle_error...;

    // Cast only needed because it's C++
    const char *data = (const char *)mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (data == MAP_FAILED)
        ...handle_error...;

    close(fd); // Don't need fd after mapping done

    // Optionally, posix_madvise(data, sb.st_size, POSIX_MADV_WILLNEED);
    // or the like will hint the OS to aggressively page in the file, so
    // count is less likely to be delayed by disk I/O

    map_size = sb.st_size;
    return data;
}

关于c++ - 在 C++ 程序中执行行计数 bash 命令(wc -l),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39518689/

相关文章:

bash - 从本地机器在远程服务器上运行脚本

c++ - 自定义 C++ boost::lambda 表达式帮助

c++ - 声明引用并传递它与仅通过引用传递一样吗?

c++ - C 和 C++ 编译器的问题

bash - 如何使用 Bash 在两个时间戳之间的文件中搜索行

bash - 如何将多个命令通过管道传输到 shell 中的单个命令? (嘘,庆典,...)

c++ - 如何获取(Linux)机器的 IP 地址?

bash - 将一个子字符串替换为 shell 脚本中的另一个字符串

bash - AWS CodeBuild buildspec bash 语法错误 : bad substitution with if statement

php - 使用 utf-8 文本输入通过 shell_exec 调用程序