C file access question

Otto J. Makela otto at tukki.jyu.fi
Fri Sep 14 17:08:38 AEST 1990


In article <28 at screamer.csee.usf.edu> stelmack at screamer.csee.usf.edu (Gregory M. Stelmack) writes:
   I've got some code I'm writing for ANSI file access, and have run into a
   problem that nobody here can help me with (I've asked). [...]

   int error=0;
   long DataLen;   /* passed to function, value checked */
   FILE *db;
   ...
   db = fopen("dd.data","rb+"); /* db is checked to make sure file opened */
   ...
   error = fseek(db,0L,2);	/* seek end of file */
   if (error==-1) return(GS_DATA_SEEK_ERROR);
   error = fwrite((char *)&DataLen,sizeof(DataLen),1,db);
   if (error!=1) return(GS_DATA_WRITE_ERROR);   <-- error = 0, so it returns
   ...
[...]

Are you sure that your cc/libc is ANSI ?  Our sun4 manuals say the following
of the "type" parameter:
          r         open for reading
          w         truncate or create for writing
          a         append: open for writing at end of  file,  or
                    create for writing
          r+        open for update (reading and writing)
          w+        truncate or create for update
          a+        append; open or create for update at EOF

Thus, no support for the ANSI 'b' mode open -- there is no such thing on
Unix, anyway (it would just be ignored).  My guess is that the non-ANSI
library fopen() starts scanning your "type" string, sees the 'b' and quits.
So, no '+' is seen and thus the write mode never gets set -> writes to the
opened file fail.

If this really is the case, you should #define different values like this:
#ifdef __STDC__
#define	OPENAPPEND	"ab+"
#else
#define	OPENAPPEND	"a+"
#endif
and then do
	dp=fopen("dd.data",OPENAPPEND)
(also, using 'a' mode means you don't have to seek the file separately)

Note that this assumes that your compiler and your library match -- both
ANSI or both non-ANSI.  If you use a mixed set, you lose...
--
* * * Otto J. Makela <otto at jyu.fi> * * * * * * * * * * * * * * * * * * * * *
* Phone: +358 41 613 847, BBS: +358 41 211 562 (CCITT, Bell 2400/1200/300) *
* Mail: Kauppakatu 1 B 18, SF-40100 Jyvaskyla, Finland, EUROPE             *
* * * Computers Rule 01001111 01001011 * * * * * * * * * * * * * * * * * * *



More information about the Comp.lang.c mailing list