On 06-Maa-02, Earnie wrote:
>> On 06-Maa-02, Mikael wrote:
>>> Are you sure the file is opened in text mode ?, use "rt" mode to be sure or
>>> set the default behavior (not sure if this is done the same way in MinGW as
>>> in VC though....)
>> Well, generally speaking, I am not sure the file is opened in text mode ("rt"),
>> but if fread() does CR/LF translation on the first ~19000 characters, then I
>> should think the file is in text mode. Certainly it is not in "rb" mode, or
>> there would be no translation at all.
> If you're expecting to use fseek/ftell and are counting bytes from the
> fread and there is \r\n translation to \n the fread will return one less
> than actually read.
About this I don't care. I use fseek/ftell to get the size of the file,
and allocate a buffer. If this buffer is too large (because CR/LF -> LF),
this does not matter. The number of bytes fread returns is not checked here,
so no problem. I do request the fseek/ftell amount of bytes with fread,
but this should not be a problem: fread is free to return less bytes,
and it should, because it should be doing the translation.
> Use this rule of thumb, if the file is easily
> creatable with NOTEPAD by the user then specify the "rt" for read text
> mode (i.e.: do \r\n translation)
"rt" is not portable. It is not in C99, at least. Portability here is an
issue, and C99 says that if the mode string is not one of the defined
ones, behaviour is undefined. Implementation is free to allow, for
example, "rt", but my code has to run on other platforms too.
In C99: mode _"r"_: open _text_ file for reading. So this should be sufficient.
So I use "r", which should do \r\n translation. And, indeed, this happens.
If I read the file in one byte at a time, I get what I want. Automatically
fgetc translates any \r\n to just \n. If I read the file, the whole file
(although I request more bytes than can be served), fread also returns
the correct result, BUT if the file is too long, the translation stops
short: beginning of the file, OK, rest not.
> otherwise specify the "rb" for read
> binary mode. If you truly have a binary file and fread finds a CNTL-Z
> (^Z) (decimal value 26) in the file, the EOF will be set.
I know this, and the files are not binary, and I don't use "rb" here.
The files I am reading are guaranteed to be text files. I have tested this
numerous times: when the file is read in, the beginning of the buffer contains
only LF codes (while the actual file has CR/LF codes). After some point, all
line feeds are CR/LF in the buffer, as in the file. Why?
Arto Huusko (arto.huusko@...) | Diving Is Fun
Divecalc @ http://divecalc.cjb.net