This section mainly details how to read, write and append to files.

Creating File Object

// Creating file object i.e. a file pointer
FILE *fptr;

Reading Files

// Creating a buffer to read input
char[100] buf;

// Open a file in read mode
fptr = fopen("file_name.txt", "r");

// NULL check for file
if (fptr == NULL) {
	printf("File not found.");
}

// This reads the file line by line
while (fgets(buf, 100, fptr) {
	printf("%s", buf);
}

Writing / Appending to Files

// Open a file in write mode
fptr = fopen("file_name.txt", "w")

// Open a file in append mode
fptr = fopen("file_name.txt", "a")

// NULL check for file
if (fptr == NULL) {
	printf("File not found.");
}

// If opened in "w" mode, text gets overwritten
// If opened in "a" mode, text gets appended to same line unless text is prefaced with
// "\\nSome text"
fprintf(fptr, "Some text");

fgets()

This is a safer version of the original gets() function which was susceptible to buffer overflow attacks.

Here is its function definition:

// We usually use stdin for stream if we want to get user input
fgets(char *buf, int n, FILE *stream)