FILE I/O & SLOW WINDOWS

Chris Calabrese[rs] cjc at ulysses.homer.nj.att.com
Tue Feb 9 02:24:57 AEST 1988


In article <11678 at brl-adm.ARPA>, VC008329%NDSUVM1.BITNET at cunyvm.cuny.EDU writes:
> 
>  I have been using Turbo C for anly a few months now and I'm having a couple
> of problems with a program I'm writing.
> 
> 
>         SAVE TO FILE                         RETRIEVE FROM FILE
>     file = fopen("main","w");           file = fopen("main","r");
>     fputs(title,file);                  fgets(title,sizeof(title),file);
>     fprintf(file,'n');                 fprintf(file,'n');
>     fputs(password,file);               fgets(password,sizeof(password),file);
>     fprintf(file,'n');                 fprintf(file,'n');
>     fputs(selpass,file);                fgets(selpass,sizeof(selpass),file);
>     fclose(file);                       fclose(file);

No, No, No, this is all wrong.

First off, the 'n's are ridiculous.  How about a newline between
variables?  Makes a lot more sense, since this is the delimiter which
fgets uses.

The next problem is that, if title is an array, the sizeof(title) 
part of the code will cause the number of characters to be read in
as had been allocated for (or until a newline), but the fputs(title,file)
part will only write as many characters as come before a '\0' char.
The sizeof code should be avoided for another reason, which is that
title may be a pointer to an array of characters, in which case
sizeof will return the number of bytes in a pointer.

Finally, when using fgets, don't forget to strip the possible \n char
on the end.

The correct code is:

SAVE TO FILE
char title[SIZE];

file = fopen("main","w");
fputs(title,file);
fputc('\n', file);
fputs(password,file);
fputc('\n', file);
fputs(selpass,file);
fputc('\n', file);
fclose(file);

Retrieve

int tmp;

file = fopen("main","r");

fgets(title, SIZE, file);
tmp = strlen(title) -1;
title[tmp] = title[tmp] == '\n' ? '\0' : title[tmp];

fgets(password, SIZE, file);
tmp = strlen(password) -1;
password[tmp] = password[tmp] == '\n' ? '\0' : password[tmp];

fgets(sellpass, SIZE, file);
tmp = strlen(sellpass) -1;
sellpass[tmp] = sellpass[tmp] == '\n' ? '\0' : sellpass[tmp];

fclose(file);


If you don't want to use \n for field seperation, use fscanf to
parse the input line for a field seperator char, or use fixed
length fields with read and write system calls.

	Chris Calabrese
	AT&T Bell Labs
	ulysses!cjc



More information about the Comp.lang.c mailing list