Skip to content

Instantly share code, notes, and snippets.

@martianboy
Last active August 29, 2015 14:11
Show Gist options
  • Save martianboy/cf55855a6734e6c8acbd to your computer and use it in GitHub Desktop.
Save martianboy/cf55855a6734e6c8acbd to your computer and use it in GitHub Desktop.
Read contents of files inside a directory
//
// main.cpp
// cpp-read-files
//
// Created by Abbas Mashayekh on 10/1/1393 AP.
// Copyright (c) 1393 Abbas Mashayekh. All rights reserved.
//
#include <iostream>
#include <dirent.h>
#include <fstream>
using namespace std;
// Burrowed from "strlib.h" provided by The Stanford C++ Libraries;
// http://stanford.edu/~stepp/cppdoc/
bool startsWith(const std::string& str, char prefix) {
return str.length() > 0 && str[0] == prefix;
}
bool startsWith(const std::string& str, const std::string& prefix) {
if (str.length() < prefix.length()) return false;
int nChars = prefix.length();
for (int i = 0; i < nChars; i++) {
if (str[i] != prefix[i]) return false;
}
return true;
}
void read_file(string path) {
ifstream ifs;
ifs.open(path);
char* buf = new char[1024];
while(!ifs.eof()) {
ifs.read(buf, 1024);
cout << buf;
}
cout << "\n\n";
}
int main(int argc, const char * argv[]) {
DIR *dir;
struct dirent *ent;
string root_path = "/Users/abbas/Projects/cpp-fs-test/data/";
if ((dir = opendir(root_path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (!startsWith(ent->d_name, '.')) {
cout << root_path + ent->d_name << endl;
read_file(root_path + ent->d_name);
}
}
}
return 0;
}
@martianboy
Copy link
Author

On Windows, you can use this light-weight implementation of POSIX dirent.h:

http://www.two-sdg.demon.co.uk/curbralan/code/dirent/dirent.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment