strigi/src/streams
fileinputstream.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include "fileinputstream.h"
00021 #include <config.h>
00022 #include <strigi/strigiconfig.h>
00023 #include <iostream>
00024 #include <cerrno>
00025 #include <cstring>
00026
00027 using namespace Strigi;
00028 using namespace std;
00029
00030 const int32_t FileInputStream::defaultBufferSize = 1048576;
00031
00032 FileInputStream::FileInputStream(const char* filepath, int32_t buffersize) {
00033 if (filepath == 0) {
00034 file = 0;
00035 m_error = "No filename was provided.";
00036 m_status = Error;
00037 return;
00038 }
00039 FILE* f = fopen(filepath, "rb");
00040 open(f, filepath, buffersize);
00041 }
00042 FileInputStream::FileInputStream(FILE* file, const char* filepath,
00043 int32_t buffersize) {
00044 open(file, filepath, buffersize);
00045 }
00046 void
00047 FileInputStream::open(FILE* f, const char* path, int32_t buffersize) {
00048
00049 file = f;
00050 filepath.assign(path);
00051 if (file == 0) {
00052
00053 m_error = "Could not read file '";
00054 m_error += filepath;
00055 m_error += "': ";
00056 m_error += strerror(errno);
00057 m_status = Error;
00058 return;
00059 }
00060
00061 if (fseeko(file, 0, SEEK_END) == -1) {
00062 m_size = -1;
00063 } else {
00064 m_size = ftello(file);
00065 fseeko(file, 0, SEEK_SET);
00066
00067
00068
00069 if (m_size == 0) {
00070 char dummy[1];
00071 size_t n = fread(dummy, 1, 1, file);
00072 if (n == 1) {
00073 m_size = -1;
00074 fseeko(file, 0, SEEK_SET);
00075 } else {
00076 fclose(file);
00077 file = 0;
00078 return;
00079 }
00080 }
00081 }
00082
00083
00084 int32_t bufsize = (m_size <= buffersize) ?m_size+1 :buffersize;
00085 setMinBufSize(bufsize);
00086 }
00087 FileInputStream::~FileInputStream() {
00088 if (file) {
00089 if (fclose(file)) {
00090
00091 m_error = "Could not close file '" + filepath + "'.";
00092 }
00093 }
00094 }
00095 int32_t
00096 FileInputStream::fillBuffer(char* start, int32_t space) {
00097 if (file == 0) return -1;
00098
00099 int32_t nwritten = fread(start, 1, space, file);
00100
00101 if (ferror(file)) {
00102 m_error = "Could not read from file '" + filepath + "'.";
00103 fclose(file);
00104 file = 0;
00105 m_status = Error;
00106 return -1;
00107 }
00108 if (feof(file)) {
00109 fclose(file);
00110 file = 0;
00111 }
00112
00113 return nwritten;
00114 }