Re: Why can't i write to a file with this code?



s. keeling wrote:

....
nj = read(fd,buffer,100);

You're going to read 100 ints (chars?) into a buffer, and the return
value from read is used as an array subscript to terminate the buffer?
Why?

$ man 2 read
....
RETURN VALUE
On success, the number of bytes read is returned (zero

I presume that read ignores all end of lines, end of strings, etc; ie it reads upto the required number of bytes (less if EOF is encountered, for example). Thus, after reading n bytes from the file, he puts a terminating nul (\0) at the end of them.

or were you wanting him to explain?
....

buffer[nj]='\0';


However, there is a bug in what he's written:

if the read fails for any reason, it'll return -1 and so he'll be splatting a nul over the byte *BEFORE* the buffer - he may be lucky in that it does no damage, but then again, he may not...

.



Relevant Pages

  • I dont mind bug: BinToHex implementation/description do not match !
    ... The BinToHex procedure occurding to Delphi's help would return a 'null' ... to terminate it with a #0 in the first place. ... Call BinToHex to convert the binary value in a buffer into a string that is ... Buffer is a buffer of bytes that contains the binary value. ...
    (alt.comp.lang.borland-delphi)
  • Re: Strange bug
    ... I'm writing a simple program to learn "C". ... but failing to terminate the line. ... to choose whether or not to flush the buffer (normally it will only ... The mainfunction returns int, ...
    (comp.lang.c)
  • Re: reading string from a text file from vc++ without MFC support
    ... You could terminate it using the return from freadby writing a '\0' into the character array. ... You should also call ReleaseBuffer() since you've modified the buffer contents and you could just pass the length returned in that call. ... It's also suspicious that you allocate CString strTitle1 on the stack then proceed to call GetLength on it before anything is assigned to it. ... That could cause you some grief as well:o) If you are reading a text file you could use CStdioFile and that will be a lot easier to manage. ...
    (microsoft.public.vc.mfc)
  • Re: proper way to determine string length
    ... If you call reador freadthe buffer is not guaranteed to be ... string, it probably won't be null-terminated and will probably ... forgetting to null terminate a string" unless you're going to try ... strings into a null-termination problem. ...
    (comp.unix.programmer)
  • Re: c dll calling vb dll
    ... SysStringLen does not account for the terminating NUL character. ... char* strings end up not being NUL-terminated. ... Another issue - you tell WideCharToMultiByte that the destination buffer ...
    (microsoft.public.vc.language)