liblinux++

A hosted C++ runtime without any libc.
git clone git://henryandlizzy.uk/liblinux++
Log | Files | Refs

ls.cpp (1010B)


      1 #include "linux.hpp"
      2 
      3 template <typename T>
      4 struct spanstack
      5 {
      6 	spanstack(span<T> st) : storage{st} {}
      7 
      8 	bool empty() const noexcept { return not n; }
      9 	bool full() const noexcept { return n == storage.size(); }
     10 	span<T const> data() noexcept { return {(T const*)storage.begin(), n}; }
     11 	void push_back(T const& v) noexcept
     12 	{
     13 		assert(not full());
     14 		storage[n++] = v;
     15 	}
     16 private:
     17 	span<T> storage;
     18 	size_t n = 0;
     19 };
     20 
     21 int main()
     22 {
     23 	auto dir = openat(AT_FDCWD, ".", O_RDONLY, 0);
     24 	assert(dir);
     25 
     26 	alignas(linux_dirent64) char buf[256];
     27 	span<char const> ios_storage[sizeof(buf)/sizeof(linux_dirent64)];
     28 	for (;;)
     29 	{
     30 		spanstack ios{span{ios_storage}};
     31 		auto res = getdents64(*dir, span{buf});
     32 		void* const end = buf + *res;
     33 		if (end == buf)
     34 			break;
     35 
     36 		for (auto ent = reinterpret_cast<linux_dirent64*>(buf); ent != end; ent = ent->next())
     37 		{
     38 			char* const name = ent->name();
     39 			size_t len = c_str{name}.length();
     40 			name[len++] = '\n';
     41 			ios.push_back({name, len});
     42 		}
     43 		*write(stdout, ios.data());
     44 	}
     45 }