Which of the following correctly implements appending to a file?
AFILE *fp = fopen("file.txt", "a");
BFILE *fp = fopen("file.txt", "w");
CFILE *fp = fopen("file.txt", "r+");
DFILE *fp = fopen("file.txt", "ab+");
Correct Answer:
A. FILE *fp = fopen("file.txt", "a");
EXPLANATION
Mode "a" opens a file for appending. New data is written at the end of the file. Mode "w" truncates the file, "r+" requires file to exist, "ab+" is appending in binary with both read/write.
Write a code snippet to read 100 bytes from a file. Which is correct?
Afread(buffer, 1, 100, fp);
Bfread(buffer, 100, 1, fp);
Cfread(buffer, 100, fp);
Dfread(100, buffer, fp);
Correct Answer:
A. fread(buffer, 1, 100, fp);
EXPLANATION
fread() syntax is fread(ptr, size, count, stream). To read 100 bytes, size=1 and count=100. Option B reads 100 items of 1 byte each, which is equivalent but less clear.
What happens when fseek() is used with SEEK_END as origin?
AFile pointer moves to end of file
BFile pointer stays at current position
CFile pointer moves to beginning
DFile is closed
Correct Answer:
A. File pointer moves to end of file
EXPLANATION
SEEK_END moves the file pointer to the end of the file. Offset can be 0 or negative to move before the end. SEEK_SET starts from beginning, SEEK_CUR from current position.