Re: Null-terminated strings: the final analysis.
- From: Flash Gordon <smap@xxxxxxxxxxxxxxxxx>
- Date: Sun, 12 Apr 2009 22:57:30 +0100
Harald van Dijk wrote:
On Sun, 12 Apr 2009 13:32:39 -0700, Keith Thompson wrote:On the systems I use, if I write a '\a' character (ASCII BEL) to a text
file, I can reasonably expect to see a '\a' character when I read it
back. The same is not true of '\0' if I use fgets() to read it (though
I think can see the '\0' if I use fgetc()).
If you use fgets, you can see any '\0' that you had previously written,
but you've got to be careful to make sure you don't treat it as a
terminator. You cannot reliably determine whether the '\0' is a
terminator,
I think you can almost all the time, but it takes a little work...
Fill buf with '\n'
if (fgets(buf,siz,file) != NULL) {
if (no '/n' in buf) {
All '\0' in buf before buf[siz-1] were read from the file
}
else {
All '\0' in buf before the '\n' were read from the file
}
}
else {
if ferror(file) {
something went wrong and buffer is indetermanate
}
else {
if buf[0]=='\n' and buf[1]=='\n' {
end-of-file encountered and no characters read
}
else if there is a '\n' in buf {
all characters before the first "\0\n" sequence were read
}
else {
don't think this should happen!
}
}
}
Any holes in my C-ish pseudo-code?
but you can reliably detect many instances where it is not: if
the bytes following '\0' have been altered by fgets, then they were read
from the file. If the bytes following '\0' have not been altered by fgets,
then you cannot be sure where they came from.
My idea is more convoluted but, I think, more reliable.
--
Flash Gordon
.
- Follow-Ups:
- Re: Null-terminated strings: the final analysis.
- From: CBFalconer
- Re: Null-terminated strings: the final analysis.
- From: Harald van Dijk
- Re: Null-terminated strings: the final analysis.
- References:
- Re: Null-terminated strings: the final analysis.
- From: Tony
- Re: Null-terminated strings: the final analysis.
- From: Mark McIntyre
- Re: Null-terminated strings: the final analysis.
- From: Mark Wooding
- Re: Null-terminated strings: the final analysis.
- From: CBFalconer
- Re: Null-terminated strings: the final analysis.
- From: Joe Wright
- Re: Null-terminated strings: the final analysis.
- From: Mark Wooding
- Re: Null-terminated strings: the final analysis.
- From: Mark McIntyre
- Re: Null-terminated strings: the final analysis.
- From: Keith Thompson
- Re: Null-terminated strings: the final analysis.
- From: Harald van Dijk
- Re: Null-terminated strings: the final analysis.
- Prev by Date: Re: Portability regarding sizeof() function
- Next by Date: Re: Falcon - powering innovation
- Previous by thread: Re: Null-terminated strings: the final analysis.
- Next by thread: Re: Null-terminated strings: the final analysis.
- Index(es):
Relevant Pages
|