C code: Part of code 1:
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <stdio.h>
#define READONLY "r"
#define UPDATE "r "
#define FALSE 0
#define TRUE 1
typedef int Boolean;
# define ERROR -1
typedef struct {
int identification ;
char name[NAMESIZE] ;
char subject[SUBJECTSIZE] ;
int grade ;
} RECORD ;
typedef struct {
char type ;
RECORD student ;
} TRANSACTION ;
typedef struct {
char occupied ;
RECORD student ;
} MASTER ;
Part of code 2 :
void main(int argc, char *argv[])
{
FILE *fpmas,*fptrans ;
int current_key ,
relative_record_number ;
boolean allocated;
TRANSACTION transaction;
MASTER master ;
clrscr();
prog = argv[0];
Part of code 3 :
int read_master_record(FILE *fp,
int relative_record_number, MASTER *master)
{
if(fseek(fp, (long) relative_record_number
*sizeof(MASTER), SEEK_SET) !=0 )
return(ERROR) ;
else if(fread((char *)master, sizeof(MASTER), 1, fp) != 1)
return(ERROR) ;
else
return(relative_record_number) ;
}
I am confused about the red mark areas(In image file I attached!) , (char *)
,!=0
and !=1
, respectively in *sizeof(MASTER), SEEK_SET) !=0 )
and else if(fread((char *)master, sizeof(MASTER), 1, fp) != 1)
. What does they meaning?! I search on those but found nothing. Can anyone present any documents on these topics or any explain?!
CodePudding user response:
First, let's break those parts down in English. Then, we can determine a meaning.
The first one:
if(fseek(fp, (long) relative_record_number
*sizeof(MASTER), SEEK_SET) !=0 )
English: Return error if the return code of fseek
is not 0. The return value of fseek
is 0 on success. Therefor, != 0
= failure.
The second statement:
else if(fread((char *)master, sizeof(MASTER), 1, fp) != 1)
The cast is unnecessary and more for documentation. It is always safe to cast any pointer to char*
. This is sort of a way to say "I'm sending this structure as raw bytes."
English: Return error if the return value of fread
is not 1. The return value of fread
:
On success, fread() and fwrite() return the number of items read
or written. This number equals the number of bytes transferred
only when size is 1. If an error occurs, or the end of the file
is reached, the return value is a short item count (or zero).
Here, we are checking if the return value != 1
. Therefor we are checking to if fread
read exactly 1 item.