Govt Exams
fprintf() is text-oriented and interprets format specifiers, potentially modifying data. It also stops at NULL characters. For binary data, fwrite() is appropriate.
File I/O uses buffering for efficiency. Data in write buffer stays in memory until fflush(fp) explicitly flushes or fclose() is called, risking data loss if program crashes.
Struct padding varies by architecture and compiler. Binary files written on one system may not read correctly on another due to different alignment. Use serialization techniques for portability.
Multiple methods exist: fseek/ftell repositions and returns position, stat() gets file info including size, and fstat() does similar with file descriptor. All are valid.
fread(buffer, size, count, fp) efficiently reads file in manageable chunks. Process each chunk, then read next. This is standard practice for large file handling.
fread() with buffer reads multiple bytes per call, reducing function call overhead. fgetc() makes 100,000 separate calls. fgets() is limited to reading up to newline.
Mixing write (fwrite - binary) and read (fprintf - formatted text) functions on same data causes mismatch. Binary data won't have format specifiers; misinterpretation results.
fflush() writes any buffered data to the underlying file. It's critical when you need to ensure data is written to disk before continuing, especially before reading the same file.
fprintf() buffers output. Without flushing (fflush() or fclose()), subsequent read operations may see incomplete data. This is a common source of bugs.
In text mode, fseek() with non-zero offset relative to SEEK_END is undefined behavior. Use fseek(fp, 0, SEEK_END) for reliable behavior.