File I/O
File I/O in hosted C goes through FILE streams: fopen to create one, fread / fwrite / fgets / fprintf to use it, and fclose to flush and release it.
Detailed Explanation
fopen(path, mode) opens a file and returns a FILE *, or NULL on failure with errno set. The mode is a string, not a bit mask. "r" reads a text file that must exist. "w" truncates or creates for writing. "a" appends. Add + for update (read and write). Add b for binary. On Unix, b has no effect. On Windows, it stops the runtime from translating '\n' to \r\n and from treating 0x1A as end of file. Use "rb" / "wb" for any file that is not meant to be edited as text.
Text versus binary is a real fork. In text mode, the number of bytes you write may not equal the number of bytes on disk, and ftell / fseek have restrictions. In binary mode, a byte is a byte. Prefer binary for anything you will fread into a struct, and still do not fread a struct if you care about portability: padding and endianness travel with the host.
fread(buf, size, nmemb, fp) returns the number of members read, which may be short on end of file or error. Distinguish those with feof and ferror. A loop that assumes fread returns nmemb or dies will mishandle a last partial record if size is not 1. Reading with size == 1 and treating the return as a byte count is the simpler contract.
fclose flushes the buffer and closes the descriptor. It can fail — a delayed write error on NFS, a full disk that only shows up at flush time. Check the return. After fclose, the FILE * is invalid. fclose(NULL) is undefined behavior in the standard; some libraries no-op it. Do not rely on that.
POSIX also offers file descriptors: open, read, write, close. They are unbuffered unless you add your own buffer. You need them for sockets, for poll, and for flags fopen cannot express. You can wrap a descriptor with fdopen when you want stdio on top.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("out.bin", "wb");
if (fp == NULL) {
perror("out.bin");
return EXIT_FAILURE;
}
unsigned char data[] = { 0x00, 0x0a, 0xff };
if (fwrite(data, 1, sizeof data, fp) != sizeof data) {
perror("fwrite");
fclose(fp);
return EXIT_FAILURE;
}
if (fclose(fp) == EOF) {
perror("fclose");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("out.bin", "rb");
if (fp == NULL) {
perror("out.bin");
return EXIT_FAILURE;
}
unsigned char buf[8];
size_t n = fread(buf, 1, sizeof buf, fp);
if (ferror(fp)) {
perror("fread");
fclose(fp);
return EXIT_FAILURE;
}
printf("read %zu bytes\n", n);
fclose(fp);
return EXIT_SUCCESS;
}Common Gotchas
Forgetting to check `fopen` for `NULL` and then using the pointer is undefined behavior
it is usually a crash, and the path that failed is the one you needed in the error message.
`fclose` can fail after a "successful" `fwrite`
the write may have sat in the buffer. Treat a failed `fclose` as a failed save.
`"w"` truncates an existing file the moment `fopen` succeeds
a crash after that point has already destroyed the previous contents. Write to a temp file and `rename`.
Mixing `fread`/`fwrite` with `fscanf`/`fprintf` on the same stream requires a flush or a seek between modes
the standard demands a file-positioning operation when you switch.