00001 #ifndef COMMONS_FILES_H
00002 #define COMMONS_FILES_H
00003
00004 #include <exception>
00005 #include <fstream>
00006 #include <iostream>
00007 #include <string>
00008 #include <vector>
00009
00010 #include <sys/types.h>
00011 #include <sys/stat.h>
00012 #include <unistd.h>
00013 #include <fcntl.h>
00014
00015 #include <commons/check.h>
00016
00017 namespace commons
00018 {
00019
00020 using namespace std;
00021
00022 class file_not_found_exception : std::exception {
00023 public:
00024 file_not_found_exception(const string & name) : name(name) {}
00025 virtual ~file_not_found_exception() throw() {}
00026 private:
00027 const string name;
00028 };
00029
00033 void read_file_as_string ( const string & name, string & out ) {
00034 ifstream in ( name.c_str() );
00035 if (in.fail()) throw file_not_found_exception( name );
00036 out = string ( istreambuf_iterator<char> ( in ), istreambuf_iterator<char>() );
00037 }
00038
00042 void read_file_as_vector ( const string & name, vector<char> & out ) {
00043 ifstream in ( name.c_str() );
00044 if ( in.fail() ) throw file_not_found_exception( name );
00045 out = vector<char> ( istreambuf_iterator<char> ( in ), istreambuf_iterator<char>() );
00046 }
00047
00054 char *
00055 load_file(const char *path, size_t & len, unsigned int ncpus)
00056 {
00057 struct stat sb;
00058 int fd = checkpass(open(path, 0));
00059
00060 check0x(fstat(fd, &sb));
00061 check(sb.st_size <= 0xffffffff);
00062
00063
00064 len = sb.st_size;
00065
00066 char *buf = new char[len + 1];
00067 checkeqnneg(pread(fd, buf, len, 0), static_cast<ssize_t>(len));
00068
00069
00070 if (false) {
00071 size_t chunk_len = len / ncpus;
00072 for (unsigned int i = 0; i < ncpus; i++) {
00073 size_t off = i * chunk_len;
00074 size_t nread = static_cast<size_t>
00075 (checknnegerr(pread(fd, buf + off, chunk_len, off)));
00076
00077 check(nread == chunk_len || off + nread == len);
00078 }
00079 }
00080
00081 check0x(close(fd));
00082
00083 buf[len] = '\0';
00084 return buf;
00085 }
00086
00087 }
00088
00089 #endif