2 * Copyright 2008, Haiku.
3 * Distributed under the terms of the MIT License.
6 * Michael Pfeiffer <laplace@users.sourceforge.net>
7 * Fredrik Modéen <fredrik@modeen.se>
9 #include "FileReadWrite.h"
15 FileReadWrite::FileReadWrite(BFile
* file
, int32 sourceEncoding
)
17 fSourceEncoding(sourceEncoding
),
24 FileReadWrite::SetEncoding(int32 sourceEncoding
)
26 fSourceEncoding
= sourceEncoding
;
31 FileReadWrite::GetEncoding() const
33 return fSourceEncoding
;
38 FileReadWrite::Write(const BString
& contents
) const
40 ssize_t written
= fFile
->Write(contents
.String(), contents
.Length());
41 if (written
!= contents
.Length())
42 return written
< 0 ? (status_t
)written
: B_IO_ERROR
;
49 FileReadWrite::Next(BString
& string
)
51 // Fill up the buffer with the first chunk of data
52 if (fPositionInBuffer
== 0)
53 fAmtRead
= fFile
->Read(&fBuffer
, sizeof(fBuffer
));
54 while (fAmtRead
> 0) {
55 while (fPositionInBuffer
< fAmtRead
) {
56 // Return true if we hit a newline or the end of the file
57 // TODO: If the source file is expected to have different encoding,
58 // don't we need to check for the line endings in that encoding?!
59 if (fBuffer
[fPositionInBuffer
] == '\n') {
61 if (fSourceEncoding
!= -1) {
63 int32 bufferLen
= string
.Length();
64 int32 destBufferLen
= bufferLen
;
65 char destination
[destBufferLen
];
66 convert_to_utf8(fSourceEncoding
, string
.String(),
67 &bufferLen
, destination
, &destBufferLen
, &state
);
72 // TODO: Adding one char at a time is very inefficient!
73 string
+= fBuffer
[fPositionInBuffer
];
77 // Once the buffer runs out, grab some more and start again
78 fAmtRead
= fFile
->Read(&fBuffer
, sizeof(fBuffer
));
79 fPositionInBuffer
= 0;