On (25 Jul 97) Wade Carpenter wrote to All...
WC> Ok.. Here's the problem. This code is meant to write 138 bytes of
WC> information to a file, "ZS.CFG" but it writes whatever is entered
WC> plus garbage, or sometimes it make a couple of extra lines, make a
WC> 139 byte file, or [ ... ]
WC> #include
WC> void main(void)
WC> {
WC> FILE *fp;
WC> char msg[88];
WC> char fspec[50];
WC> fp = fopen("ZS.CFG","wt");
WC> fwrite(gets(msg),88,1,fp);
WC> fwrite(gets(fspec),50,1,fp);
WC> fclose(fp);
WC> printf("Done!\r\n");
WC> }
Okay, a couple of things are at work causing your problems here. First
of all, when you use fread/fwrite, you generally want to open the files
as binary rather than text - on DOS, opening the file in text mode will
expand your newline characters to carriage return/linefeed pairs. This
is most likely the source of your files being larger than expected.
The other problem you're seeing, with getting garbage at the end of
what's entered is harder to really cure. The situation's really fairly
simple. When you create `msg' and `fspec', they're both full of
whatever garbage happens to be on the stack at that time. When you call
gets, it fills up that memory up to as many characters as were entered.
It than adds a '\0' to the end to indicate the end of the string. If
there was space after that in the array, (e.g. you entered half as many
characters as there are in the array) they're left with whatever garbage
they previously contained.
The real question at this point is what you want to do about it. Your
primary choices are to fill the remainder of the array with a known
value before writing it, or to not worry about the format of the file -
even with garbage there, a matching program will read in the same string
as you wrote out, and the garbage on the end will be ignored. If your
file has to fit a specific binary format, this may not be possible.
Finally, since you're posting this in the C++ echo, I'm guess you really
want an answer that involves using C++ rather than pure C. This should
be at least pretty close to what you want:
#include
int main(void) {
char msg[80] = {0}; // really clears the entire array to 0's.
char fspec[50] {0};
ofstream fp("zs.cfg", ios::write | ios::binary);
cin.getline(msg, 80);
cin.getline(fspec, 50);
fp.write(msg, 80);
fp.write(fspec, 50);
fp.close();
return !fp.good();
}
Later,
Jerry.
... The Universe is a figment of its own imagination.
--- PPoint 1.90
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)
|