On Mon, 7 Apr 2008 22:25:18 -0700 (PDT), lector
<ha***************@gmail.comwrote:
>Do you think it will make things even more efficient if I read and
write data in binary and in chunks of bytes ? I'm doing this using
fread and fwrite functions. eg. something like below
Writing one large chunk as opposed to several small chunks usually
means less calls to the I/O functions which usually means less
overhead for those calls. This has nothing to do with binary vs text.
If you built a large string containing the text equivalent of your
structure members, you would achieve the same efficiency with regard
to calling I/O functions without the problems introduced by binary
noted below.
>
/*-------------------- WRITES EMPLOYEE RECORDS TO A BINARY
FILE-----------------------*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char another = 'Y';
typedef struct emp_struct
{
char name[40];
int age;
float bs;
} emp;
emp e;
fp = fopen("EMP.DAT", "wb");
if(fp == NULL)
{
puts("Cannot open file");
exit(EXIT_FAILURE);
}
while(another == 'Y')
{
printf("\nEnter name, age and basic salary\n");
scanf("%s %d %f", e.name, &e.age, &e.bs);
This opens up the possibility of the user entering more than 39
characters into name. This will not support a name which contains an
embedded blank. You really should check that scanf returns 3.
> fwrite(&e, sizeof(e), 1, fp);
If you change compilers, or possibly even compiler options, the file
may be difficult to process because of different padding in the
structure. If you transport the file to a different system, the int
and the float may have problems due to endian-ness or representation.
>
printf("Add another record (Y/N)");
fflush(stdin);
fflush is not defined for input streams.
> another = getchar();
What will you do if the user enters 'y'?
On most interactive systems, the user will need to press Enter after
typing the 'Y'. This will leave a '\n' in the buffer. When you go
back to the scanf, this character will be processed immediately and
the user will never be able to enter the three values.
}
fclose(fp);
return 0;
}
Remove del for email