From: "Glynne Casteel" Newsgroups: comp.os.msdos.djgpp Subject: Re: Binary File Operations Date: Sun, 13 Sep 1998 11:47:04 -0600 Organization: ICGNetcom Lines: 43 Message-ID: <6th0is$94m@dfw-ixnews5.ix.netcom.com> References: <1998091221320200 DOT RAA14256 AT ladder01 DOT news DOT aol DOT com> NNTP-Posting-Host: den-co74-123.ix.netcom.com To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk IIibanezII wrote in message <1998091221320200 DOT RAA14256 AT ladder01 DOT news DOT aol DOT com>... >I have been trying to learn binary file operations by making a file that gets a >string as input and writes it to a binary file, and then a second program which >reads from a binary file. Could someone please tell me what I am doing wrong? >Here's the code: > >char string[100]; >FILE *test; >test = fopen("test.dat", "wb"); > >fgets(string, 1, stdin); >fwrite(string, 1, 100, test); >fclose(test) > To avoid these kinds of problems, you should use I/O functions that are meant to be used together. When working with binary data, use fwrite() for output and use fread() for input. When working with string data, use fprintf() or fputs() for output and use fgets() for input. Some other points to remember: - fgets() will usually return a newline just before the null terminator, unless the input string exceeds the maximum specified buffer length; you'll probably want to trim it before you work with the string. - fread() returns a count of how much data was read; you'll want to use this value to avoid data that was not placed in the buffer by the current read operation. Even though your buffer is 100 bytes long, fread() may only fill the first 22 bytes with data, the remaining bytes are unaltered. Glynne