Language = C. Please give an answer with explanation. 22. A binary file stores a
ID: 3707144 • Letter: L
Question
Language = C. Please give an answer with explanation.
22. A binary file stores a list of company's salaries. Each salary is stored as double. Which code fragment below will read the third salary record in the file into a variable sal. The file is already opened using the file description fid. a. fseek (fid, 0, SEEK SET); fread(&sal;, sizeof double), 1, fid); b. fseek(fid, 0, SEEK_END) rc ftell(fid); fseek(fid, rc 3*sizeof(double), SEEK_END); fread(&sal;, sizeof(double), 1, fid); fseek(fid, 0, SEEK_SET); rc - ftell(fid) fseek(fid, rc 2*sizeof (double), SEEK_CUR); fread(&sal;, sizeof double), 1, fid); c. d. fseek(fid, 0, SEEK_SET) fseek(fid, 2* sizeof double), SEEK_CUR); fread(&sal;, sizeof double), 1, fid); e. None of the aboveExplanation / Answer
the ANS is option d.
the format for fseek in c is this fseek(FILE *stream,long int offset,int whence). so here stream is the pointer to a FILE object that identifies the stream, offset is the number of bytes to offset from whence so it is added to whence to set the cursor in the file to the position from where we have to read, whence is the position from where the offset is added. So in option (d) SEEK_SET(beginning of file) and SEEK_CUR(current postion of file pointer) is used. fseek(fid,0,SEEK_SET) sets the cursor to the beginning of the file since SEEK_SET is used here, where 0 is added to whence because we don't have to move from that cursor location and fid is just used for file stream which is the pointer to the file object. Now fseek(fid,2*sizeof(double),SEEK_CUR); is the second line. we have to read the 3rd salary record and they are all in double so we are calculating the offset of the first two record by using sizeof() which returns the size of double in this case. so offset will be 2*sizeof(double) where double is 8 bytes. Now this offset is added to SEEK_CUR where SEEK_CUR returns the current position of pointer which was previously set to the beginning so adding offset of 2 double records will set the current pointer to the 3rd record. Then finally the 3rd record is read using fread(&sal,sizeof(double),1,fid); where 1st element(&sal) is a pointer second element(sizeof(double)) is the size in bytes of element to be read, 1 is the number of elements to be read(we are reading only the 3rd element hence 1), and fid is the stream which is pointer to the file object.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.