1 /* 2 * Copyright 2008, Haiku. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Michael Pfeiffer <laplace@users.sourceforge.net> 7 * Fredrik Modéen <fredrik@modeen.se> 8 */ 9 10 #include "FileReadWrite.h" 11 12 #include <UTF8.h> 13 #include <Path.h> 14 15 FileReadWrite::FileReadWrite(BFile *file, int32 sourceEncoding) 16 : fFile(file), 17 fSourceEncoding(sourceEncoding) 18 {} 19 20 21 void 22 FileReadWrite::SetEncoding(int32 sourceEncoding) 23 { 24 fSourceEncoding = sourceEncoding; 25 } 26 27 28 uint32 29 FileReadWrite::GetEncoding() 30 { 31 return fSourceEncoding; 32 } 33 34 35 status_t 36 FileReadWrite::Write(const BString& contents)const 37 { 38 ssize_t sz = fFile->Write(contents.String(), contents.Length()); 39 if (sz != contents.Length()) 40 return sz < 0 ? sz : B_IO_ERROR; 41 else 42 return B_OK; 43 } 44 45 46 bool 47 FileReadWrite::Next(BString& string) 48 { 49 // Fill up the buffer with the first chunk of code 50 if (fPositionInBuffer == 0) 51 fAmtRead = fFile->Read(&fBuffer, sizeof(fBuffer)); 52 while (fAmtRead > 0) { 53 while (fPositionInBuffer < fAmtRead) { 54 // Return true if we hit a newline or the end of the file 55 if (fBuffer[fPositionInBuffer] == '\n') { 56 fPositionInBuffer++; 57 //Convert begin 58 int32 state = 0; 59 int32 bufferLen = string.Length(); 60 int32 destBufferLen = bufferLen; 61 char destination[destBufferLen]; 62 if (fSourceEncoding) 63 convert_to_utf8(fSourceEncoding, string.String(), &bufferLen, destination, &destBufferLen, &state); 64 string = destination; 65 return true; 66 } 67 string += fBuffer[fPositionInBuffer]; 68 fPositionInBuffer++; 69 } 70 71 // Once the buffer runs out, grab some more and start again 72 fAmtRead = fFile->Read(&fBuffer, sizeof(fBuffer)); 73 fPositionInBuffer = 0; 74 } 75 return false; 76 } 77