File Handling MCQs in C Language

File Handling MCQs in C Language

  1. Which fopen mode 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.

  1. 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_CUR moves relative to current; SEEK_SET is absolute from start; ftell returns position but doesn’t move pointer.

  1. What does ftell(fp) return on success?
    A. Number of bytes until EOF
    B. The current file offset as long
    C. 0 or 1 depending on EOF
    D. File size in bytes always
    Answer: B
    Solution: ftell returns current file position (offset from start) as long. It can be used with fseek.

  1. 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.

  1. If fgetc(fp) returns EOF and feof(fp) is false, what is likely true?
    A. Error occurred; check ferror(fp)
    B. End of file reached
    C. File pointer is NULL
    D. File closed automatically
    Answer: A
    Solution: fgetc returning EOF could mean error or EOF. If feof false, check ferror — an error likely occurred.

  1. 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: clearerr clears EOF and error flags; rewind sets position to start and clears error too — but clearerr is explicit for the flags.

  1. What happens when you fseek(fp, 0, SEEK_END) then ftell?
    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).

  1. 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: fwrite writes raw memory; fprintf/fputs expect strings; putc writes a single character.

  1. 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.

  1. Which is true about text vs binary modes in standard C on POSIX systems?
    A. They differ; binary translates \n to \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.

  1. 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 use open with O_CREAT|O_EXCL
    D. "a"
    Answer: C
    Solution: "wx" (C11) requests exclusive creation; POSIX open with O_CREAT|O_EXCL ensures atomic create.

  1. Which function returns nonzero if an error indicator is set for stream?
    A. feof
    B. ferror
    C. clearerr
    D. errno
    Answer: B
    Solution: ferror tests error indicator; feof tests EOF.

  1. 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. fread fixed size once
    Answer: A
    Solution: fgets reads up to buffer; for very long lines need loop/realloc. fscanf("%s") breaks on whitespace.

  1. 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: fflush flushes user-space buffers to kernel/device; on input streams behavior is implementation-defined.

  1. What is returned by fgetc(fp) on success?
    A. char
    B. unsigned char
    C. int (converted from unsigned char)
    D. void*
    Answer: C
    Solution: fgetc returns int so it can return EOF distinct from any unsigned char value.

  1. 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 10 ints into array a.

  1. 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 by fread
    B. Swap byte order for multi-byte types after reading
    C. Use fprintf instead of fwrite
    D. Use ftell and fseek to change endianness
    Answer: B
    Solution: fread doesn’t change endianness. Code must convert (byte-swap) when necessary.

  1. 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 arbitrary fseek and write.

  1. What is the correct way to check whether fopen failed?
    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: fopen returns NULL on failure; perror prints reason. if (!fp) is common shorthand.

  1. Which function rewinds fp and 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.

  1. While copying text file to another file using fgetc and fputc, 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. Use fprintf for both
    D. Use fseek frequently
    Answer: B
    Solution: To copy bytes exactly (prevent newline translation), open both in binary mode ("rb"/"wb").

  1. Which call will cause undefined behavior?
    A. fseek(fp, 0, SEEK_SET); where fp is 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: Passing NULL as buffer to fwrite is undefined. fflush(stdin) is undefined per standard (implementation-defined). fclose twice is undefined too. B is clearly invalid.

  1. 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. gets is unsafe and removed.

  1. If you fseek(fp, 10, SEEK_SET); then fwrite(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: fseek positions pointer at offset 10; writing 5 bytes writes offsets 10..14.

  1. In text mode, which of these may be true?
    A. ftell returns file offset in bytes always identical to read count
    B. ftell may return an opaque value not directly usable as byte count on some systems
    C. fseek can’t be used in text mode at all
    D. feof clears automatically after fseek
    Answer: B
    Solution: In text mode, ftell/fseek semantics may be implementation-defined and not necessarily byte offsets.

  1. How to create a temporary file securely?
    A. Use tmpfile()
    B. Use fopen("temp.txt","w+")
    C. Use system("mktemp") only
    D. Use remove("temp.txt") then fopen
    Answer: A
    Solution: tmpfile() creates a unique temporary file opened as binary stream, removed on close. mkstemp (POSIX) is another secure option.

  1. 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: remove deletes directory entry; on POSIX open handles keep the file until closed; behavior can vary on other OSes.

  1. Which is true about fread return value n when reading nmemb elements?
    A. Always equals nmemb
    B. n is count of fully read members; partial members count as zero
    C. n can be negative on error
    D. n is 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.

  1. 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, fread returns 0. If partial data matters, use fread with byte counts and examine feof/ferror.

  1. If fprintf(fp, "%d", x); is used, how many bytes are written?
    A. Exactly sizeof(x) bytes
    B. Depends on decimal digit count of x — variable length
    C. Always 4 bytes for int
    D. One per loop iteration
    Answer: B
    Solution: fprintf writes textual representation; number of bytes equals number of characters printed.

  1. Which is true about setvbuf?
    A. It can set a custom buffer and mode (fully, line, none) for a stream
    B. Cannot be used on stdout
    C. Must be called after first I/O on the stream
    D. Replaces file content with buffer contents
    Answer: A
    Solution: setvbuf customizes buffering—must be called before any I/O on the stream.

  1. Which is recommended when writing a database file to guarantee consistency?
    A. Write directly to target file and fflush, rely on OS
    B. Write to a temporary file, fflush/fsync, then rename to target — atomic replace
    C. Use fopen(...,"a") only
    D. Use buffered writes without fflush
    Answer: B
    Solution: Write to temp file and atomic rename reduces corruption risk; fsync (POSIX) forces data to disk.

  1. What is the effect of freopen("new.txt","w", stdin);?
    A. Redirects stdin to new.txt for reading only
    B. Reopens stdin as new.txt in write mode replacing content, subsequent reads from stdin will read from the file (but opened for writing so behavior is tricky)
    C. Closes and reassigns stdin stream to new.txt; using "w" for stdin is allowed but generally unusual. Better: use "r" to read.
    D. Undefined per standard
    Answer: C
    Solution: freopen replaces the stdin stream with file. Mode "w" opens for writing so further reads are problematic; technically allowed but not useful.

  1. To check whether file fp is 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: feof detects EOF indicator, set after an attempted read that reached EOF. ftell doesn’t return EOF.

  1. 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 adding b / t are standard modifiers in C11; x exists in C11 as exclusive create when combined like "wx".

  1. 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: fwrite writes block efficiently. putc is slower. fseek doesn’t write bytes.

  1. 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.

  1. Which is true about mixing fscanf and fgets on the same stream?
    A. Always safe with no additional handling
    B. After fscanf that leaves newline, fgets may read the remaining newline — use fgetc or consume newline first
    C. fgets converts binary to text automatically
    D. fscanf resets EOF flag automatically
    Answer: B
    Solution: fscanf may leave newline in buffer; subsequent fgets might read empty line. Consume newline or use consistent input functions.

  1. Which statement about fprintf and fwrite is correct?
    A. fprintf is for formatted text; fwrite writes binary raw data.
    B. fprintf writes fixed-size binary, fwrite only for text.
    C. Both are identical under the hood.
    D. Only fwrite sets errno on failure.
    Answer: A
    Solution: fprintf serializes formatted text; fwrite writes raw bytes.

  1. While reading a file using fscanf(fp, "%d", &x) — on encountering a non-digit char, fscanf will:
    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: fscanf stops at first unmatched input; the non-digit remains for next read; return value indicates how many items were assigned.

  1. What does fdopen(fd, "w") do?
    A. Converts file descriptor to FILE * stream for buffered IO in the given mode
    B. Converts FILE to file descriptor
    C. Creates a duplicate descriptor only for read
    D. Undefined if fd >= 0
    Answer: A
    Solution: fdopen wraps an existing file descriptor into a FILE* for stdio operations.

  1. Which of these guarantees no data loss even if the program crashes after fclose?
    A. fflush before fclose
    B. fclose ensures buffers are written but may not flush to disk cache; to guarantee durable persistence, fsync on descriptor is needed (POSIX).
    C. fflush without fsync is sufficient on all systems
    D. fwrite alone guarantees persistence
    Answer: B
    Solution: fclose flushes stdio buffers but OS may still cache writes; fsync forces disk; combine fflush and fsync on descriptor.

  1. Which returns pointer to buffer which must be freed after use and contains file contents?
    A. freadall(fp) — not standard
    B. Use fseek/ftell to get size, allocate buffer, fread entire file — user must free buffer
    C. fgets auto-allocates memory always
    D. gets returns heap pointer
    Answer: B
    Solution: Standard method: fseek(fp,0,SEEK_END); size=ftell(fp); rewind(fp); malloc(size+1); fread(...); Then free.

  1. What should you check immediately after fwrite to 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 and ferror for errors.

  1. Which of these may invalidate pointer returned by fgets?
    A. Closing the file fclose(fp) after fgets but before using buffer — buffer remains valid if on heap or stack; fgets writes 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: fgets writes into a user-provided buffer; freeing it or overwriting it invalidates pointer/content.

  1. Which is true for tmpnam function?
    A. It’s safe for secure temporary file creation always
    B. It may be insecure (race) — prefer tmpfile() or mkstemp()
    C. It deletes the file it creates automatically
    D. It returns a file descriptor
    Answer: B
    Solution: tmpnam may produce predictable names; tmpfile/mkstemp are safer.

  1. What happens if you fseek to a position beyond EOF and then fwrite some 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.

  1. Which C standard library function can truncate a file to a specified length?
    A. truncate() (POSIX) or _chsize on Windows — not standard C; no standard C function for truncation.
    B. ftruncate (POSIX)
    C. freopen
    D. fseek with size and fwrite zeros
    Answer: A/B dependent — best: B (POSIX ftruncate)
    Solution: Standard C has no direct truncate; POSIX provides truncate/ftruncate.

  1. Which is true about reading text files with fread?
    A. fread can read the bytes fine; it doesn’t interpret text lines — fgets is line oriented.
    B. fread converts newline characters to \n
    C. fread stops at newline only
    D. fread is only for binary files and prohibited for text files
    Answer: A
    Solution: fread reads raw bytes irrespective of content; it’s okay for text if you manage buffers.

  1. Which is best practice to avoid resource leakage when opening files in functions?
    A. Always fclose file before every return (use single exit point or goto cleanup)
    B. Rely on OS to close at program exit only
    C. Let garbage collector handle it
    D. Use global FILE* and never close
    Answer: A
    Solution: Close files promptly; use consistent cleanup patterns (single exit/goto or C99+ cleanup macros).

  1. Which returns nonzero if stream is line buffered?
    A. setvbuf returns buffering mode
    B. No standard way to query buffering mode portably
    C. isatty(fileno(fp)) suggests line buffering if stdout and terminal — but not definitive.
    D. fgetpos returns buffering status
    Answer: B (portable)
    Solution: Standard C lacks API to query buffer mode. isatty heuristic possible but not guaranteed.

  1. If you fopen("file.txt","r+") and then fprintf(fp, "Hello"); with no fseek or fflush, what happens if you then call fgets on same fp?
    A. Behavior undefined — mixing input and output on same stream requires intervening fflush, fseek, or repositioning per standard.
    B. Works fine always
    C. fgets will read the text just written automatically
    D. fgets will always fail
    Answer: A
    Solution: Standard requires a file positioning operation (fflush, fseek, or fgetpos) between write and subsequent read unless write ends with newline in some implementations.

  1. 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 introduced x to indicate exclusive create: "wx" or "w+x"; POSIX open with O_CREAT|O_EXCL is an alternative.

  1. Given char buf[20]; fgets(buf, 20, fp); what happens if a line has 25 chars + newline?
    A. fgets reads 19 chars + NUL; remainder stays in stream for next call
    B. fgets reads all 26 chars anyway
    C. Buffer overflow occurs
    D. fgets discards rest of line automatically
    Answer: A
    Solution: fgets reads at most n-1 chars, NUL terminates; rest remains.

  1. Which causes undefined behavior when using ftell?
    A. Calling ftell on a text stream after reading/writing without an intervening fseek? Not necessarily; using ftell on text streams can be implementation-defined but generally allowed.
    B. Using ftell on closed stream definitely UB.
    C. Calling ftell before fopen
    D. Both B and C
    Answer: D
    Solution: ftell requires a valid open stream — closed or NULL stream is UB.

  1. When copying a binary file, which is faster generally?
    A. Reading/writing single bytes in loop with fgetc/fputc
    B. Block reads/writes with fread/fwrite using a sizable buffer (e.g., 8KB)
    C. Line by line with fgets/fputs
    D. Using fprintf for each byte
    Answer: B
    Solution: Block IO reduces system calls and is faster.

  1. 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 must fflush and fseek appropriately.
    B. Open "w" then fread
    C. Append impossible in C
    D. Use fprintf then rewind always
    Answer: A
    Solution: "a+" allows read and append, but writes may always go to end; position and flush appropriately before read.

  1. 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 or fgets to avoid overflow.

  1. What does setbuf(fp, NULL) do?
    A. Disables buffering for stream fp
    B. Sets buffer to NULL then crash always
    C. Allocates zero-sized buffer
    D. No effect
    Answer: A
    Solution: setbuf(fp, NULL) makes stream unbuffered (same as setvbuf(fp, NULL, _IONBF, 0)).

  1. If fread is used to read char s[10] and returns 7, what may be true?
    A. 7 bytes successfully read; maybe EOF reached; check feof/ferror.
    B. Always indicates an error only.
    C. Buffer too small for data.
    D. Means file size is 7 always.
    Answer: A
    Solution: Check feof/ferror to understand cause.

  1. 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 use ftruncate on fd then rewind if necessary.

  1. Which code reads entire file into dynamically-sized string using only standard C and fgets?
    A. Loop fgets into buffer and realloc append until EOF — yes, works.
    B. fread once — only if size known.
    C. gets unlimited — unsafe.
    D. scanf("%a") — nonstandard.
    Answer: A
    Solution: Repeated fgets and realloc is standard and safe approach.

  1. Which is true: fopen("file","r") then remove("file") on POSIX does what?
    A. Immediately deletes file and fp becomes invalid
    B. Removes directory entry; existing open descriptor can still access file contents until closed
    C. remove fails 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.

  1. 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.

  1. Which guarantees thread-safety of FILE* operations in C11?
    A. Concurrent access to same FILE* from multiple threads is safe only if accessed through flockfile/funlockfile or serialized by user — C11 guarantees per-thread locking in many implementations but best practice is to lock around shared FILE*.
    B. Always safe no locking needed
    C. Always unsafe no matter what
    D. Use fopen per thread only
    Answer: A
    Solution: Use flockfile/funlockfile or other synchronization when multiple threads access same FILE*.

  1. Which yields portable code: reading/writing double between programs?
    A. Use text fprintf/fscanf to write and read decimal representation — portable across endian/size differences (within precision).
    B. fwrite raw double bytes — 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.

  1. Which is true of fputc?
    A. It writes one unsigned char converted to unsigned char stored as int param and returns written character as unsigned char cast to int or EOF on error.
    B. It writes a string.
    C. It writes binary blocks.
    D. It always flushes stream.
    Answer: A
    Solution: fputc signature and behavior as described.

  1. Which causes implementation-defined behavior in text mode?
    A. Using fseek with offset and SEEK_SET to any value not returned by ftell in text mode may be implementation-defined.
    B. Using fopen in text mode
    C. Using fread for binary data
    D. Using fprintf to print integers
    Answer: A
    Solution: Text-mode file positioning has implementation-defined behavior for ftell offsets.

  1. Which is correct to safely print binary data as hex to text file?
    A. Loop over bytes and fprintf(fp, "%02X", buf[i]);
    B. Use fwrite to text file (will include nonprintables)
    C. Use printf only to stdout
    D. Use fscanf to write
    Answer: A
    Solution: Printing hex as text preserves binary content in textual form.

  1. Which of these can cause deadlocks when writing to the same file from multiple processes?
    A. Using fopen without file locking — concurrency issues possible
    B. Using flock or fcntl record locking correctly avoids races
    C. Using append without atomicity assumption may still be atomic per POSIX for writes less than PIPE_BUF? Actually POSIX guarantees O_APPEND writes are atomic for each write syscall but fwrite buffered 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.

  1. 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”.


  1. Which is necessary to convert between binary data and platform-independent representation?
    A. Use htonl/ntohl for integer endianness conversion for 32-bit fields when writing to platform-independent binary format.
    B. Just fwrite is enough.
    C. Use memcpy only.
    D. Use fprintf only.
    Answer: A
    Solution: Use explicit endianness conversion functions or write text.

  1. Which is true about tmpfile()?
    A. Returns FILE* already opened and unlinked; automatically removed on fclose or program exit.
    B. Requires user to call remove explicitly.
    C. Returns filename string.
    D. Only available on Windows.
    Answer: A
    Solution: tmpfile() creates anonymous temporary file removed upon close.

  1. Which is correct if fread reads fewer items than requested and feof returns false?
    A. Likely an error — check ferror(fp) for the error reason.
    B. EOF occurred always
    C. Buffer too small
    D. fread always reads full items if available
    Answer: A
    Solution: If feof false, but fewer bytes read, an error likely occurred.

  1. Which statement about fgetpos/fsetpos is true?
    A. They use an opaque type fpos_t suitable for text stream positioning and may store other state (like multibyte conversion state); prefer them for portability over ftell in some cases.
    B. fgetpos returns file size
    C. They are obsolete
    D. fpos_t is always long
    Answer: A
    Solution: fpos_t may hold more than offset; used to save and restore position portably.

  1. 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.

  1. 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 raw fwrite of 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.

  1. 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.

  1. Which is true about fprintf return value?
    A. Returns number of characters printed (excluding terminating null) or negative on error.
    B. Always returns 0
    C. Returns pointer to FILE
    D. Returns EOF on success
    Answer: A
    Solution: fprintf returns number of characters written or negative value on error.

  1. What is the result of fputs("abc", fp); fputc('\n', fp); compared to fprintf(fp, "abc\n");?
    A. Both produce same output abc\n but fprintf is formatted and may be slower depending on implementation.
    B. Different always.
    C. fputs adds null terminator to file.
    D. fputc overwrites fputs.
    Answer: A
    Solution: Both write same characters. fputs + fputc may be faster if no formatting needed.

  1. 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 target then delete tmpfile
    D. Overwrite target in place always safer
    Answer: A
    Solution: rename is atomic replacement if source & target are on same filesystem.

  1. Which is correct when reading variable length records separated by newline safely?
    A. Use getline(&buf, &len, fp) if available; otherwise loop fgets with dynamic realloc when buffer fills.
    B. Use fscanf("%s")
    C. Use getc only
    D. Use gets
    Answer: A
    Solution: getline handles arbitrary length; fallback use fgets + grow.

  1. What is the effect of fflush(NULL) in POSIX?
    A. Flushes all open output streams.
    B. Undefined behavior.
    C. Flushes only stdin.
    D. Closes all streams.
    Answer: A
    Solution: POSIX specifies fflush(NULL) flushes all output streams. Standard C leaves it undefined; but many implementations support it.

  1. Which is correct if you need to check if file is a regular file or directory?
    A. Use stat and check S_ISREG(st_mode) (POSIX)
    B. fopen and fread to test
    C. fseek will tell you
    D. Use fgets
    Answer: A
    Solution: Use stat or fstat and check mode bits.

  1. Which risk is avoided by opening files with fopen(path, "rb") on Windows when reading binary?
    A. Newline conversion from \r\n to \n which 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.

  1. Which of the following is true about fprintf(stderr, ...)?
    A. stderr is unbuffered by default (or line-buffered when connected to terminal) so messages appear immediately.
    B. stderr is fully buffered always.
    C. stderr is closed by default.
    D. Writing to stderr writes to a file named stderr.
    Answer: A
    Solution: stderr is typically unbuffered; use for error messages for prompt display.

  1. Which is a correct method to detect if file write failed due to disk full?
    A. After fwrite, check return value and then ferror(fp) and inspect errno for ENOSPC.
    B. feof will be set to ENOSPC
    C. ftell returns negative on disk full
    D. Nothing can detect disk full
    Answer: A
    Solution: Check fwrite return and ferror, then errno shows ENOSPC on POSIX.

  1. Which of the following modifications of file pointer is portable?
    A. Using fgetpos then fsetpos to restore position even on text streams — portable.
    B. Using ftell and storing returned long for later fseek in 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/fsetpos are preferred for portability.

  1. Which is true about line endings when using fgets on Windows in text mode?
    A. \r\n converts to \n and fgets returns buffer ending with \n only — conversion by runtime.
    B. fgets returns \r\n unmodified in text mode.
    C. fgets strips newline always.
    D. fgets crashes on Windows.
    Answer: A
    Solution: Text mode usually translates \r\n to \n for C library.

  1. Which is correct to write binary data reliably even if interrupted by signals?
    A. Use write system call with proper checks and loop on partial writes (POSIX) — fwrite may hide partial writes due to buffering.
    B. Use fwrite alone — always atomic.
    C. Use fprintf
    D. Use fputc per byte only
    Answer: A
    Solution: For robustness against interruptions, use low-level write and loop handling EINTR.

  1. Which of these is a danger when using scanf("%[^\n]", buf)?
    A. Buffer overflow if no width limit specified.
    B. scanf leaves newline in input; may cause next read issues.
    C. Both A and B.
    D. scanf always safe.
    Answer: C
    Solution: Always include width specifier and handle newline.

  1. 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 with fprintf each field — also possible but slower.
    C. Both are valid; A is direct binary write.
    D. Using memcpy only without file IO.
    Answer: C
    Solution: Both approaches valid; fwrite is direct binary dump.

  1. 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 attempt rename and check error.
    B. First stat then rename always safe
    C. remove then rename
    D. fopen then rename
    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.

  1. 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 into p, works fine.
    C. Allocates memory automatically.
    D. Only safe if file is empty.
    Answer: A
    Solution: %s requires pointer to writable memory; passing NULL causes UB.

  1. 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: _IONBF disables buffering; call before any IO.

  1. Which method is best to safely read numbers separated by commas (CSV-like) ignoring whitespace?
    A. Use fgets line-by-line and strtok/strtol/strtod to parse.
    B. fscanf(fp,"%d,",&x) repeatedly — fragile.
    C. fread raw 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 with strtol/strtod.

  1. 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: Using FILE* after fclose is UB.

  1. 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. fflush alone is enough always.
    C. rename automatically flushes data.
    D. fclose alone ensures persistence.
    Answer: A
    Solution: fflush flushes stdio buffers; fsync ensures kernel writes to disk; then rename for atomic replace.

  1. Which of the following is allowed by standard C when opening a file for update?
    A. fopen("x","r+") and then using both fread and fwrite with proper positioning between switching — allowed.
    B. Simultaneous fread and fwrite without any fseek/fflush between — 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.

  1. 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.