Govt. Exams
Entrance Exams
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.
fread() returns the number of complete items successfully read, not the number of bytes. It will return 500 even if 1000 were requested.
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.