Re: Null-terminated strings: the final analysis.



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
.



Relevant Pages

  • Re: Is this string input function safe?
    ... return a pointer to mallocated memory holding one input string, ... See my comment after your call to fgets. ... char* malloc_getstr ... before any characters are read, then the ...
    (comp.lang.c)
  • Regarding: fgets() replacement
    ... > shortcomings of fgets(). ... Your algorithm can end up calling realloc O) times. ... set of characters read (with the exception of the last one that might ... Paul Hsieh ...
    (comp.lang.c)
  • Re: Is C99 the final C? (some suggestions)
    ... fgets was designed to read text lines into a string. ... that fgetsdoes not ignore embedded null characters in text files. ... and puts it in the buffer nominated. ...
    (comp.lang.c)
  • Re: File Viewer that stops at the 24th line
    ... > I need some major help with this code I have for a file viewer. ... On the first pass through the loop, buf is still uninitialized. ... of each line of the file), fgets includes that character in the ... non-terminal character in the string. ...
    (comp.lang.c)
  • Re: about getch()
    ... discards characters until it sees a '\n'. ... Neither getsnor fgets() solves the problem. ... additional characters will be ... all you're doing is using the "event loop" of fgetsto break out of the ...
    (comp.lang.c)