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