File Handling MCQs in C Language
- Which
fopenmode opens a file for reading and writing and creates the file if it does not exist, but does not truncate it if it exists?
A."r+"
B."w+"
C."a+"
D."rx"
Answer: C
Solution:"r+"requires existing file;"w+"truncates;"a+"opens for read/write, creates if absent, and appends—does not truncate."rx"is non-standard POSIX mode requiring existing file.
- Given
FILE *fp = fopen("data.bin","rb");which function correctly moves the file pointer 32 bytes forward from current position?
A.fseek(fp, 32, SEEK_SET);
B.fseek(fp, 32, SEEK_CUR);
C.fseek(fp, -32, SEEK_CUR);
D.ftell(fp) + 32;
Answer: B
Solution:SEEK_CURmoves relative to current;SEEK_SETis absolute from start;ftellreturns position but doesn’t move pointer.
- What does
ftell(fp)return on success?
A. Number of bytes until EOF
B. The current file offset aslong
C. 0 or 1 depending on EOF
D. File size in bytes always
Answer: B
Solution:ftellreturns current file position (offset from start) aslong. It can be used withfseek.
- Which call truncates the file to zero length when opening?
A.fopen("x.txt", "r")
B.fopen("x.txt", "w")
C.fopen("x.txt", "r+")
D.fopen("x.txt", "a")
Answer: B
Solution:"w"opens for writing and truncates existing file to zero length;"a"appends;"r+"needs file present, doesn’t truncate.
- If
fgetc(fp)returnsEOFandfeof(fp)is false, what is likely true?
A. Error occurred; checkferror(fp)
B. End of file reached
C. File pointer is NULL
D. File closed automatically
Answer: A
Solution:fgetcreturningEOFcould mean error or EOF. Iffeoffalse, checkferror— an error likely occurred.
- Which function clears the error and EOF indicators on stream
fp?
A.clearerr(fp)
B.rewind(fp)
C.fseek(fp, 0, SEEK_SET)
D.fclose(fp)
Answer: A
Solution:clearerrclears EOF and error flags;rewindsets position to start and clears error too — butclearerris explicit for the flags.
- What happens when you
fseek(fp, 0, SEEK_END)thenftell?
A. Returns 0
B. Returns file size in bytes
C. Undefined behavior
D. Returns negative value
Answer: B
Solution: Seeking to end and ftell returns offset from start = file size (in bytes for binary streams).
- Which is safest to write binary structure
struct S s;to a file?
A.fprintf(fp, "%s", (char*)&s);
B.fwrite(&s, sizeof(s), 1, fp);
C.fputs((char*)&s, fp);
D.putc((char*)&s, fp);
Answer: B
Solution:fwritewrites raw memory;fprintf/fputsexpect strings;putcwrites a single character.
- Given
fwrite(buf,1,20,fp);returns 12 — what does it mean?
A. 12 bytes were written successfully
B. 12 is error code
C. Only 12 bytes remain in buffer
D. File is full and closed
Answer: A
Solution: Return value is number of elements successfully written — here bytes — so 12 bytes written.
- Which is true about text vs binary modes in standard C on POSIX systems?
A. They differ; binary translates\nto\r\n
B. No difference on POSIX; difference exists on Windows
C. Text mode is deprecated on all systems
D. Binary mode auto-detects encoding
Answer: B
Solution: On POSIX there’s no difference; on Windows text mode translates newlines. C standard allows differences.
- To atomically create a file only if it doesn’t exist, which fopen mode is appropriate on POSIX?
A."w"
B."r"
C."wx"or useopenwithO_CREAT|O_EXCL
D."a"
Answer: C
Solution:"wx"(C11) requests exclusive creation; POSIXopenwithO_CREAT|O_EXCLensures atomic create.
- Which function returns nonzero if an error indicator is set for stream?
A.feof
B.ferror
C.clearerr
D.errno
Answer: B
Solution:ferrortests error indicator;feoftests EOF.
- Which pattern reads lines robustly (including very long lines)?
A.fgets(buf, sizeof buf, fp)in loop — but checks return and reallocates if truncated
B.fscanf(fp, "%s", buf)
C.getc(fp)only once
D.freadfixed size once
Answer: A
Solution:fgetsreads up to buffer; for very long lines need loop/realloc.fscanf("%s")breaks on whitespace.
- Which does
fflush(fp)do for output streams?
A. Flushes output buffer to file/device
B. Closes file
C. Clears EOF flag
D. Moves file pointer to end
Answer: A
Solution:fflushflushes user-space buffers to kernel/device; on input streams behavior is implementation-defined.
- What is returned by
fgetc(fp)on success?
A.char
B.unsigned char
C.int(converted fromunsigned char)
D.void*
Answer: C
Solution:fgetcreturnsintso it can returnEOFdistinct from anyunsigned charvalue.
- Which correctly reads 10 integers from a binary file into array
a?
A.fread(a, sizeof(int), 10, fp);
B.fread(a, 1, 10*sizeof(char), fp);
C.fread(&a, sizeof(a), 1, fp);
D.fscanf(fp, "%d", a);
Answer: A
Solution:fread(a, sizeof(int), 10, fp)reads 10ints into arraya.
- If a binary file was written on a little-endian machine and read on big-endian machine, what must be done?
A. Nothing; bytes are auto-converted byfread
B. Swap byte order for multi-byte types after reading
C. Usefprintfinstead offwrite
D. Useftellandfseekto change endianness
Answer: B
Solution:freaddoesn’t change endianness. Code must convert (byte-swap) when necessary.
- Which mode allows writing at arbitrary positions without truncation?
A."w"
B."r+"or"r+b"
C."w+"
D."a"
Answer: B
Solution:"r+"opens for read/write without truncation, allowing arbitraryfseekand write.
- What is the correct way to check whether
fopenfailed?
A.if (fp == NULL) { perror("fopen"); }
B.if (fp == 0) ...
C.if (!fp) exit(1);(equivalent to A)
D. All of A and C are acceptable; B is less clear but equivalent on many systems
Answer: A (and C is acceptable style)
Solution:fopenreturnsNULLon failure;perrorprints reason.if (!fp)is common shorthand.
- Which function rewinds
fpand clears error/EOF indicators in one call?
A.fseek(fp, 0, SEEK_SET); clearerr(fp);
B.rewind(fp)
C.ftell(fp)
D.rewindfile(fp)
Answer: B
Solution:rewind(fp)sets file position to beginning and clears errors.
- While copying text file to another file using
fgetcandfputc, which of the following must be done to preserve content exactly (on Windows)?
A. Open both files in text mode
B. Open both files in binary mode
C. Usefprintffor both
D. Usefseekfrequently
Answer: B
Solution: To copy bytes exactly (prevent newline translation), open both in binary mode ("rb"/"wb").
- Which call will cause undefined behavior?
A.fseek(fp, 0, SEEK_SET);wherefpis valid
B.fwrite(NULL, 1, 10, fp);
C.fclose(fp); fclose(fp);
D.fflush(stdin);
Answer: B or D — trick question; best answer B
Solution: PassingNULLas buffer tofwriteis undefined.fflush(stdin)is undefined per standard (implementation-defined).fclosetwice is undefined too. B is clearly invalid.
- Which function can be used to get line from file including arbitrary length safely in GNU C?
A.getline(&buf, &n, fp)
B.fgets(buf, n, fp)only
C.scanf("%[^\n]")
D.gets
Answer: A
Solution:getline(POSIX/GNU) allocates/reallocates buffer to fit the line.getsis unsafe and removed.
- If you
fseek(fp, 10, SEEK_SET);thenfwrite(buf,1,5,fp);where was data written?
A. At offset 5
B. At offset 10–14
C. At the end of file only
D. Undefined location
Answer: B
Solution:fseekpositions pointer at offset 10; writing 5 bytes writes offsets 10..14.
- In text mode, which of these may be true?
A.ftellreturns file offset in bytes always identical to read count
B.ftellmay return an opaque value not directly usable as byte count on some systems
C.fseekcan’t be used in text mode at all
D.feofclears automatically afterfseek
Answer: B
Solution: In text mode,ftell/fseeksemantics may be implementation-defined and not necessarily byte offsets.
- How to create a temporary file securely?
A. Usetmpfile()
B. Usefopen("temp.txt","w+")
C. Usesystem("mktemp")only
D. Useremove("temp.txt")thenfopen
Answer: A
Solution:tmpfile()creates a unique temporary file opened as binary stream, removed on close.mkstemp(POSIX) is another secure option.
- What does
remove("a.txt")do on success?
A. Deletes filename immediately; file closed if open?
B. Returns 0 and removes directory entry; if file is open, behavior is implementation-defined on some systems
C. Always fails if file is open
D. Truncates file but leaves name
Answer: B
Solution:removedeletes directory entry; on POSIX open handles keep the file until closed; behavior can vary on other OSes.
- Which is true about
freadreturn valuenwhen readingnmembelements?
A. Always equalsnmemb
B.nis count of fully read members; partial members count as zero
C.ncan be negative on error
D.nis number of bytes read, not elements
Answer: B
Solution:fread(ptr, size, nmemb, fp)returns number of full elements read. Partial element is not counted.
- Which is correct to read binary file of unknown struct count:
struct X x; while (fread(&x, sizeof x, 1, fp) == 1)— what potential problem?
A. None, always safe
B. If file truncated, last partial struct lost (fread returns 0) — must detect and handle partial read if needed
C. Works only in text mode
D. fseek required between reads
Answer: B
Solution: If file ends with a partial struct,freadreturns 0. If partial data matters, usefreadwith byte counts and examinefeof/ferror.
- If
fprintf(fp, "%d", x);is used, how many bytes are written?
A. Exactlysizeof(x)bytes
B. Depends on decimal digit count ofx— variable length
C. Always 4 bytes for int
D. One per loop iteration
Answer: B
Solution:fprintfwrites textual representation; number of bytes equals number of characters printed.
- Which is true about
setvbuf?
A. It can set a custom buffer and mode (fully, line, none) for a stream
B. Cannot be used onstdout
C. Must be called after first I/O on the stream
D. Replaces file content with buffer contents
Answer: A
Solution:setvbufcustomizes buffering—must be called before any I/O on the stream.
- Which is recommended when writing a database file to guarantee consistency?
A. Write directly to target file andfflush, rely on OS
B. Write to a temporary file,fflush/fsync, thenrenameto target — atomic replace
C. Usefopen(...,"a")only
D. Use buffered writes withoutfflush
Answer: B
Solution: Write to temp file and atomicrenamereduces corruption risk;fsync(POSIX) forces data to disk.
- What is the effect of
freopen("new.txt","w", stdin);?
A. Redirectsstdintonew.txtfor reading only
B. Reopensstdinasnew.txtin write mode replacing content, subsequent reads from stdin will read from the file (but opened for writing so behavior is tricky)
C. Closes and reassignsstdinstream tonew.txt; using"w"forstdinis allowed but generally unusual. Better: use"r"to read.
D. Undefined per standard
Answer: C
Solution:freopenreplaces thestdinstream with file. Mode"w"opens for writing so further reads are problematic; technically allowed but not useful.
- To check whether file
fpis at EOF, which call is correct?
A.if (feof(fp)) ...after read attempt
B.if (ftell(fp) == EOF)
C.if (ferror(fp)) ...
D.if (fp == NULL)
Answer: A
Solution:feofdetects EOF indicator, set after an attempted read that reached EOF.ftelldoesn’t return EOF.
- Which of these is NOT a standard C file opening mode?
A."wb+"
B."r+x"
C."a"
D."rb"
Answer: B
Solution:"r+x"isn’t standard;"r+","w+", and addingb/tare standard modifiers in C11;xexists in C11 as exclusive create when combined like"wx".
- How to write 100 zeros (bytes) into a binary file efficiently?
A.for(i=0;i<100;i++) putc(0,fp);
B.char z[100] = {0}; fwrite(z, 1, 100, fp);
C.fprintf(fp, "\0\0...")with 100 nulls typed out
D.fseek(fp, 100, SEEK_SET);
Answer: B
Solution:fwritewrites block efficiently.putcis slower.fseekdoesn’t write bytes.
- Which standard function can be used to get file descriptor from
FILE *?
A.fileno(fp)(POSIX)
B.fdesc(fp)
C.fdopen(fp)
D.getfd(fp)
Answer: A
Solution:fileno(POSIX) returns underlying file descriptor. Not standard C but widely available.
- Which is true about mixing
fscanfandfgetson the same stream?
A. Always safe with no additional handling
B. Afterfscanfthat leaves newline,fgetsmay read the remaining newline — usefgetcor consume newline first
C.fgetsconverts binary to text automatically
D.fscanfresets EOF flag automatically
Answer: B
Solution:fscanfmay leave newline in buffer; subsequentfgetsmight read empty line. Consume newline or use consistent input functions.
- Which statement about
fprintfandfwriteis correct?
A.fprintfis for formatted text;fwritewrites binary raw data.
B.fprintfwrites fixed-size binary,fwriteonly for text.
C. Both are identical under the hood.
D. Onlyfwritesetserrnoon failure.
Answer: A
Solution:fprintfserializes formatted text;fwritewrites raw bytes.
- While reading a file using
fscanf(fp, "%d", &x)— on encountering a non-digit char,fscanfwill:
A. Skip it and continue reading next integer
B. Stop and return number of items scanned so far; non-digit remains in input
C. Remove the character from stream silently
D. Crash program
Answer: B
Solution:fscanfstops at first unmatched input; the non-digit remains for next read; return value indicates how many items were assigned.
- What does
fdopen(fd, "w")do?
A. Converts file descriptor toFILE *stream for buffered IO in the given mode
B. ConvertsFILEto file descriptor
C. Creates a duplicate descriptor only for read
D. Undefined if fd >= 0
Answer: A
Solution:fdopenwraps an existing file descriptor into aFILE*for stdio operations.
- Which of these guarantees no data loss even if the program crashes after
fclose?
A.fflushbeforefclose
B.fcloseensures buffers are written but may not flush to disk cache; to guarantee durable persistence,fsyncon descriptor is needed (POSIX).
C.fflushwithoutfsyncis sufficient on all systems
D.fwritealone guarantees persistence
Answer: B
Solution:fcloseflushes stdio buffers but OS may still cache writes;fsyncforces disk; combinefflushandfsyncon descriptor.
- Which returns pointer to buffer which must be freed after use and contains file contents?
A.freadall(fp)— not standard
B. Usefseek/ftellto get size, allocate buffer,freadentire file — user must free buffer
C.fgetsauto-allocates memory always
D.getsreturns heap pointer
Answer: B
Solution: Standard method:fseek(fp,0,SEEK_END); size=ftell(fp); rewind(fp); malloc(size+1); fread(...);Then free.
- What should you check immediately after
fwriteto detect write errors?
A.if (fwrite(...) < nmemb) { if (ferror(fp)) /* handle */ }
B.if (feof(fp))
C.if (fp == NULL)
D. Nothing; writes always succeed
Answer: A
Solution: Check returned count andferrorfor errors.
- Which of these may invalidate pointer returned by
fgets?
A. Closing the filefclose(fp)afterfgetsbut before using buffer — buffer remains valid if on heap or stack;fgetswrites into user-supplied buffer so closing file doesn’t invalidate buffer.
B. Freeing the buffer if it was dynamically allocated.
C. Overwriting buffer subsequently.
D. B and C.
Answer: D
Solution:fgetswrites into a user-provided buffer; freeing it or overwriting it invalidates pointer/content.
- Which is true for
tmpnamfunction?
A. It’s safe for secure temporary file creation always
B. It may be insecure (race) — prefertmpfile()ormkstemp()
C. It deletes the file it creates automatically
D. It returns a file descriptor
Answer: B
Solution:tmpnammay produce predictable names;tmpfile/mkstempare safer.
- What happens if you
fseekto a position beyond EOF and thenfwritesome data?
A. Behavior undefined
B. Creates a file hole (sparse file) filling with zeros on many systems and writes data starting at that offset
C. Always fails with error
D. Moves to EOF instead
Answer: B
Solution: On many filesystems, seeking past EOF and writing creates a hole (reads as zeros). It depends on filesystem semantics.
- Which C standard library function can truncate a file to a specified length?
A.truncate()(POSIX) or_chsizeon Windows — not standard C; no standard C function for truncation.
B.ftruncate(POSIX)
C.freopen
D.fseekwith size andfwritezeros
Answer: A/B dependent — best: B (POSIXftruncate)
Solution: Standard C has no direct truncate; POSIX providestruncate/ftruncate.
- Which is true about reading text files with
fread?
A.freadcan read the bytes fine; it doesn’t interpret text lines —fgetsis line oriented.
B.freadconverts newline characters to\n
C.freadstops at newline only
D.freadis only for binary files and prohibited for text files
Answer: A
Solution:freadreads raw bytes irrespective of content; it’s okay for text if you manage buffers.
- Which is best practice to avoid resource leakage when opening files in functions?
A. Alwaysfclosefile before everyreturn(use single exit point orgotocleanup)
B. Rely on OS to close at program exit only
C. Let garbage collector handle it
D. Use globalFILE*and never close
Answer: A
Solution: Close files promptly; use consistent cleanup patterns (single exit/goto or C99+cleanupmacros).
- Which returns nonzero if stream is line buffered?
A.setvbufreturns buffering mode
B. No standard way to query buffering mode portably
C.isatty(fileno(fp))suggests line buffering ifstdoutand terminal — but not definitive.
D.fgetposreturns buffering status
Answer: B (portable)
Solution: Standard C lacks API to query buffer mode.isattyheuristic possible but not guaranteed.
- If you
fopen("file.txt","r+")and thenfprintf(fp, "Hello");with nofseekorfflush, what happens if you then callfgetson samefp?
A. Behavior undefined — mixing input and output on same stream requires interveningfflush,fseek, or repositioning per standard.
B. Works fine always
C.fgetswill read the text just written automatically
D.fgetswill always fail
Answer: A
Solution: Standard requires a file positioning operation (fflush,fseek, orfgetpos) between write and subsequent read unless write ends with newline in some implementations.
- Which correctly opens file with exclusive creation (fail if exists) in C11?
A.fopen("a.txt","r+")
B.fopen("b.txt","wx")
C.fopen("c.txt","w")
D.open("d.txt", O_CREAT)
Answer: B
Solution: C11 introducedxto indicate exclusive create:"wx"or"w+x"; POSIXopenwithO_CREAT|O_EXCLis an alternative.
- Given
char buf[20]; fgets(buf, 20, fp);what happens if a line has 25 chars + newline?
A.fgetsreads 19 chars + NUL; remainder stays in stream for next call
B.fgetsreads all 26 chars anyway
C. Buffer overflow occurs
D.fgetsdiscards rest of line automatically
Answer: A
Solution:fgetsreads at mostn-1chars, NUL terminates; rest remains.
- Which causes undefined behavior when using
ftell?
A. Callingftellon a text stream after reading/writing without an interveningfseek? Not necessarily; usingftellon text streams can be implementation-defined but generally allowed.
B. Usingftellon closed stream definitely UB.
C. Callingftellbeforefopen
D. Both B and C
Answer: D
Solution:ftellrequires a valid open stream — closed orNULLstream is UB.
- When copying a binary file, which is faster generally?
A. Reading/writing single bytes in loop withfgetc/fputc
B. Block reads/writes withfread/fwriteusing a sizable buffer (e.g., 8KB)
C. Line by line withfgets/fputs
D. Usingfprintffor each byte
Answer: B
Solution: Block IO reduces system calls and is faster.
- How to append to a file and then reposition to read newly appended data?
A. Use"a+"mode, but note that on some systems writing is forced to end; to read what you just wrote, you mustfflushandfseekappropriately.
B. Open"w"thenfread
C. Append impossible in C
D. Usefprintfthenrewindalways
Answer: A
Solution:"a+"allows read and append, but writes may always go to end; position and flush appropriately before read.
- Which is true when you use
fscanf(fp,"%s",s)to read token?
A. It will read whitespace-delimited token and may overflow if no width specifier — dangerous.
B. It reads entire line including spaces.
C. It is safe always.
D. It returns EOF always on success.
Answer: A
Solution: Use width specifier orfgetsto avoid overflow.
- What does
setbuf(fp, NULL)do?
A. Disables buffering for streamfp
B. Sets buffer toNULLthen crash always
C. Allocates zero-sized buffer
D. No effect
Answer: A
Solution:setbuf(fp, NULL)makes stream unbuffered (same assetvbuf(fp, NULL, _IONBF, 0)).
- If
freadis used to readchar s[10]and returns 7, what may be true?
A. 7 bytes successfully read; maybe EOF reached; checkfeof/ferror.
B. Always indicates an error only.
C. Buffer too small for data.
D. Means file size is 7 always.
Answer: A
Solution: Checkfeof/ferrorto understand cause.
- Which is valid to move file pointer to beginning and zero-length file?
A.freopen(NULL, "w", fp)— invalid
B.ftruncate(fileno(fp), 0); rewind(fp);(POSIX)
C.fseek(fp,0,SEEK_SET)— only moves pointer, does not change file length
D.fprintf(fp, "\0")— writes null but expands file
Answer: B
Solution: To truncate open file to zero length useftruncateon fd thenrewindif necessary.
- Which code reads entire file into dynamically-sized string using only standard C and
fgets?
A. Loopfgetsinto buffer andreallocappend until EOF — yes, works.
B.freadonce — only if size known.
C.getsunlimited — unsafe.
D.scanf("%a")— nonstandard.
Answer: A
Solution: Repeatedfgetsandreallocis standard and safe approach.
- Which is true:
fopen("file","r")thenremove("file")on POSIX does what?
A. Immediately deletes file andfpbecomes invalid
B. Removes directory entry; existing open descriptor can still access file contents until closed
C.removefails because file is open
D. File becomes zero-length
Answer: B
Solution: On POSIX, deleting an open file removes name but keeps file contents accessible until last descriptor closed.
- Which is correct to check number of bytes in file
fp?
A.fseek(fp, 0, SEEK_END); long size = ftell(fp); rewind(fp);
B.while(fgetc(fp)!=EOF) count++;— works but slow.
C. Both A and B valid; A gives size in bytes quickly, but careful with text-mode on some platforms.
D.sizeof(fp)
Answer: C
Solution: A is typical; B also works but slower;sizeof(fp)returns size of pointer type.
- Which guarantees thread-safety of
FILE*operations in C11?
A. Concurrent access to sameFILE*from multiple threads is safe only if accessed throughflockfile/funlockfileor serialized by user — C11 guarantees per-thread locking in many implementations but best practice is to lock around sharedFILE*.
B. Always safe no locking needed
C. Always unsafe no matter what
D. Usefopenper thread only
Answer: A
Solution: Useflockfile/funlockfileor other synchronization when multiple threads access sameFILE*.
- Which yields portable code: reading/writing
doublebetween programs?
A. Use textfprintf/fscanfto write and read decimal representation — portable across endian/size differences (within precision).
B.fwriterawdoublebytes — not portable across endianness/representation.
C. Use canonical representation (e.g., IEEE-754 text or network binary) for portability.
D. All of the above, depending on tradeoffs.
Answer: D
Solution: Text is portable; raw binary isn’t. Use canonical formats for portability.
- Which is true of
fputc?
A. It writes oneunsigned charconverted tounsigned charstored asintparam and returns written character asunsigned charcast tointorEOFon error.
B. It writes a string.
C. It writes binary blocks.
D. It always flushes stream.
Answer: A
Solution:fputcsignature and behavior as described.
- Which causes implementation-defined behavior in text mode?
A. Usingfseekwith offset andSEEK_SETto any value not returned byftellin text mode may be implementation-defined.
B. Usingfopenin text mode
C. Usingfreadfor binary data
D. Usingfprintfto print integers
Answer: A
Solution: Text-mode file positioning has implementation-defined behavior forftelloffsets.
- Which is correct to safely print binary data as hex to text file?
A. Loop over bytes andfprintf(fp, "%02X", buf[i]);
B. Usefwriteto text file (will include nonprintables)
C. Useprintfonly to stdout
D. Usefscanfto write
Answer: A
Solution: Printing hex as text preserves binary content in textual form.
- Which of these can cause deadlocks when writing to the same file from multiple processes?
A. Usingfopenwithout file locking — concurrency issues possible
B. Usingflockorfcntlrecord locking correctly avoids races
C. Usingappendwithout atomicity assumption may still be atomic per POSIX for writes less than PIPE_BUF? Actually POSIX guaranteesO_APPENDwrites are atomic for eachwritesyscall butfwritebuffered behavior is more complex.
D. A and C partial — best answer: A (risky)
Answer: A
Solution: Without locking, race conditions and corruption can occur. Use proper interprocess locking.
- What will this print?
FILE *fp = fopen("t.txt","w+");
fprintf(fp,"Hello\n");
fseek(fp,0,SEEK_SET);
char s[10];
fgets(s,10,fp);
printf("%s", s);
A. Hello
B. Nothing
C. Undefined because w+ cannot read
D. Hello\n including newline
Answer: A (prints Hello\n then printf shows Hello followed by newline — effectively prints Hello)
Solution: w+ allows read/write; after fprintf using fseek before fgets is correct. fgets reads “Hello\n”.
- Which is necessary to convert between binary data and platform-independent representation?
A. Usehtonl/ntohlfor integer endianness conversion for 32-bit fields when writing to platform-independent binary format.
B. Justfwriteis enough.
C. Usememcpyonly.
D. Usefprintfonly.
Answer: A
Solution: Use explicit endianness conversion functions or write text.
- Which is true about
tmpfile()?
A. ReturnsFILE*already opened and unlinked; automatically removed onfcloseor program exit.
B. Requires user to callremoveexplicitly.
C. Returns filename string.
D. Only available on Windows.
Answer: A
Solution:tmpfile()creates anonymous temporary file removed upon close.
- Which is correct if
freadreads fewer items than requested andfeofreturns false?
A. Likely an error — checkferror(fp)for the error reason.
B. EOF occurred always
C. Buffer too small
D.freadalways reads full items if available
Answer: A
Solution: Iffeoffalse, but fewer bytes read, an error likely occurred.
- Which statement about
fgetpos/fsetposis true?
A. They use an opaque typefpos_tsuitable for text stream positioning and may store other state (like multibyte conversion state); prefer them for portability overftellin some cases.
B.fgetposreturns file size
C. They are obsolete
D.fpos_tis alwayslong
Answer: A
Solution:fpos_tmay hold more than offset; used to save and restore position portably.
- Why is
fopen("file","rb+")different from"r+b"?
A. They are equivalent — both mean read/write binary without truncation.
B. One opens for append only
C. One truncates file
D. One fails always
Answer: A
Solution: Mode order doesn’t matter; they are equivalent.
- Which technique handles file updates when structure size has changed between versions?
A. Use textual, versioned file format (e.g., JSON, tagged fields) to ensure backward compatibility.
B. Use rawfwriteof struct — brittle.
C. Use checksums and field tags.
D. A and C combined.
Answer: D
Solution: Textual or versioned binary formats with tags/checksums maintain compatibility.
- Which of the following is correct to determine if a file exists?
A.fp = fopen("x", "r"); if (fp) { fclose(fp); /* exists */ }
B.access("x", F_OK)(POSIX)
C.stat("x", &st)(POSIX)
D. Any of the above; be mindful of race conditions between check and use.
Answer: D
Solution: Several ways exist; checking then using may introduce race.
- Which is true about
fprintfreturn value?
A. Returns number of characters printed (excluding terminating null) or negative on error.
B. Always returns 0
C. Returns pointer to FILE
D. ReturnsEOFon success
Answer: A
Solution:fprintfreturns number of characters written or negative value on error.
- What is the result of
fputs("abc", fp); fputc('\n', fp);compared tofprintf(fp, "abc\n");?
A. Both produce same outputabc\nbutfprintfis formatted and may be slower depending on implementation.
B. Different always.
C.fputsadds null terminator to file.
D.fputcoverwritesfputs.
Answer: A
Solution: Both write same characters.fputs+fputcmay be faster if no formatting needed.
- To atomically replace a file on POSIX after writing to temp, which is correct?
A.rename("tmpfile", "target")— atomic replace semantics on POSIX if same filesystem.
B.remove("target"); rename("tmpfile", "target")— not atomic.
C.copy tmpfile to targetthen delete tmpfile
D. Overwrite target in place always safer
Answer: A
Solution:renameis atomic replacement if source & target are on same filesystem.
- Which is correct when reading variable length records separated by newline safely?
A. Usegetline(&buf, &len, fp)if available; otherwise loopfgetswith dynamic realloc when buffer fills.
B. Usefscanf("%s")
C. Usegetconly
D. Usegets
Answer: A
Solution:getlinehandles arbitrary length; fallback usefgets+ grow.
- What is the effect of
fflush(NULL)in POSIX?
A. Flushes all open output streams.
B. Undefined behavior.
C. Flushes onlystdin.
D. Closes all streams.
Answer: A
Solution: POSIX specifiesfflush(NULL)flushes all output streams. Standard C leaves it undefined; but many implementations support it.
- Which is correct if you need to check if file is a regular file or directory?
A. Usestatand checkS_ISREG(st_mode)(POSIX)
B.fopenandfreadto test
C.fseekwill tell you
D. Usefgets
Answer: A
Solution: Usestatorfstatand check mode bits.
- Which risk is avoided by opening files with
fopen(path, "rb")on Windows when reading binary?
A. Newline conversion from\r\nto\nwhich changes byte offsets and content — using binary prevents this translation.
B. File being locked.
C. File permissions automatically changed.
D. EOF detection disabled.
Answer: A
Solution: Binary mode disables newline translation on Windows.
- Which of the following is true about
fprintf(stderr, ...)?
A.stderris unbuffered by default (or line-buffered when connected to terminal) so messages appear immediately.
B.stderris fully buffered always.
C.stderris closed by default.
D. Writing tostderrwrites to a file named stderr.
Answer: A
Solution:stderris typically unbuffered; use for error messages for prompt display.
- Which is a correct method to detect if file write failed due to disk full?
A. Afterfwrite, check return value and thenferror(fp)and inspecterrnoforENOSPC.
B.feofwill be set to ENOSPC
C.ftellreturns negative on disk full
D. Nothing can detect disk full
Answer: A
Solution: Checkfwritereturn andferror, thenerrnoshowsENOSPCon POSIX.
- Which of the following modifications of file pointer is portable?
A. Usingfgetposthenfsetposto restore position even on text streams — portable.
B. Usingftelland storing returnedlongfor laterfseekin text mode — may be implementation-defined.
C. Both A and B, but A is preferred on text streams.
D. Neither A nor B.
Answer: C
Solution:fgetpos/fsetposare preferred for portability.
- Which is true about line endings when using
fgetson Windows in text mode?
A.\r\nconverts to\nandfgetsreturns buffer ending with\nonly — conversion by runtime.
B.fgetsreturns\r\nunmodified in text mode.
C.fgetsstrips newline always.
D.fgetscrashes on Windows.
Answer: A
Solution: Text mode usually translates\r\nto\nfor C library.
- Which is correct to write binary data reliably even if interrupted by signals?
A. Usewritesystem call with proper checks and loop on partial writes (POSIX) —fwritemay hide partial writes due to buffering.
B. Usefwritealone — always atomic.
C. Usefprintf
D. Usefputcper byte only
Answer: A
Solution: For robustness against interruptions, use low-levelwriteand loop handlingEINTR.
- Which of these is a danger when using
scanf("%[^\n]", buf)?
A. Buffer overflow if no width limit specified.
B.scanfleaves newline in input; may cause next read issues.
C. Both A and B.
D.scanfalways safe.
Answer: C
Solution: Always include width specifier and handle newline.
- How to read and write a struct array of 50 elements to file
db.bin?
A.fwrite(arr, sizeof arr[0], 50, fp);after opening file in"wb"— correct.
B. Loop withfprintfeach field — also possible but slower.
C. Both are valid; A is direct binary write.
D. Usingmemcpyonly without file IO.
Answer: C
Solution: Both approaches valid;fwriteis direct binary dump.
- Which code snippet safely renames a file only if the process has write permission?
A.if (access("old", W_OK) == 0) rename("old","new");— race possible; better to attemptrenameand check error.
B. Firststatthenrenamealways safe
C.removethenrename
D.fopenthenrename
Answer: A (but note race)
Solution: Checking access is not race-free. Best is to attempt operation and handle EACCES/EINVAL errors; but A shows permission check.
- Which results in undefined behavior:
char *p = NULL; fscanf(fp, "%s", p);
A. Undefined due to passing NULL as destination buffer for%s.
B. Reads string intop, works fine.
C. Allocates memory automatically.
D. Only safe if file is empty.
Answer: A
Solution:%srequires pointer to writable memory; passingNULLcauses UB.
- Which is true about
setvbuf(fp, buf, _IONBF, 0)?
A. Sets stream unbuffered; must be called before I/O.
B. Sets stream to line-buffered.
C. Sets buffer size to 0 but still buffered.
D. Does nothing in standard C.
Answer: A
Solution:_IONBFdisables buffering; call before any IO.
- Which method is best to safely read numbers separated by commas (CSV-like) ignoring whitespace?
A. Usefgetsline-by-line andstrtok/strtol/strtodto parse.
B.fscanf(fp,"%d,",&x)repeatedly — fragile.
C.freadraw then parse manually — possible but complex.
D. Both A and C possible; A is simpler and safer.
Answer: D (A preferred)
Solution: Read lines and parse tokens robustly withstrtol/strtod.
- What is the consequence of writing to a file stream after
fclose(fp)?
A. Undefined behavior — must not use closed streams.
B. It will re-open automatically.
C. It will silently fail but program continues.
D. It will flush buffer automatically.
Answer: A
Solution: UsingFILE*afterfcloseis UB.
- Which combination ensures data is persisted to physical disk on POSIX before rename?
A.fflush(fp); fsync(fileno(fp)); fclose(fp); rename(tmp, target);— flush and sync ensure data on disk before rename.
B.fflushalone is enough always.
C.renameautomatically flushes data.
D.fclosealone ensures persistence.
Answer: A
Solution:fflushflushes stdio buffers;fsyncensures kernel writes to disk; thenrenamefor atomic replace.
- Which of the following is allowed by standard C when opening a file for update?
A.fopen("x","r+")and then using bothfreadandfwritewith proper positioning between switching — allowed.
B. Simultaneousfreadandfwritewithout anyfseek/fflushbetween — undefined.
C. Both A and B depending on implementation — but standard requires syncing, so A is correct practice.
D. Neither are allowed.
Answer: C (A is correct practice)
Solution: Standard requires an intervening file positioning function or flush when switching between input and output.
- Final tricky one — consider:
FILE *fp = fopen("file","w+");
fwrite("ABC", 1, 3, fp);
fseek(fp, -2, SEEK_CUR);
fwrite("XY", 1, 2, fp);
fseek(fp, 0, SEEK_SET);
char buf[10]; fread(buf,1,3,fp);
buf[3]='\0';
printf("%s\n", buf);
What prints?
A. ABC
B. AXYC
C. ACY
D. AXY
Answer: D
Solution: Step by step: write “ABC” → file: A B C ; fseek -2 from current pos (after writing 3 bytes) moves to position 1 (0-based): that’s at ‘B’. fwrite("XY", ...) writes X at pos1 and Y at pos2 → file becomes A X Y . fseek(0) then fread 3 bytes gives “AXY”. So prints AXY.