Reading Files
// fopen(file name, 'r' for read, 'w' for write, 'a' for append)
// - Return null on error
FILE *f = fopen("file_name", "r");
if (f == NULL) {
// Process error
}
// fclose(FILE) returns 0 on success.
fclose(f);
// fgets(char* return, int maximum length of line, FILE): Read a line
// - Return null on error
// - Maximum length incudes the termination character
char line[41];
while (fgets(line, 40, stdin) != NULL) {
// Do something with line
}
// fscanf(FILE, char* format, *argument pointers...)
// - Returns the number of values read
char name[81]; int age;
while (fscanf(f, "%80s %d", name, &age) == 2) {
// Do something
}
Writing Files
FILE *f = fopen("file_name", "w");
// fprintf(FILE, char* content)
// - Append a line to the file buffer, DOESN'T WRITE IMMEDIATELY
fprintf(f, "Hello World\\n");
// Flush: Make sure line buffer is properly written
fflush(f);
// Open in binary mode (rb / wb)
FILE *f = fopen("file_name", "rb");
// fwrite(void* data, size of each element, length of data array, FILE)
// - Return n elements written, 0 on error
int a[5] = {1, 2, 3, 4, 5};
fwrite(a, sizeof(int), sizeof(a) / sizeof(int), f);
// fread(void* ptr, size of each element, length of data array, FILE)
// - Return n elements read, 0 on error
int b[5];
fread(a, sizeof(int), sizeof(a) / sizeof(int), f);
// fseek(FILE, int offset, int mode)
// - Mode can be
// SEEK_SET: Set absolute position
// SEEK_CUR: Set relative position from current position
// SEEK_END: Set relative position from the end of the file
fseek(f, 0, SEEK_SET);