File Pointers

Important stdio.h Functions

fopen()

FILE* ptr1 = fopen("read.txt", "r");
FILE* ptr2 = fopen("write.txt", "w");
FILE* ptr3 = fopen("append.txt", "a");

fclose()

fclose(ptr1);

fgetc()

char ch = fgetc(ptr1);
// `cat` command: read all the characters from a file and print them to the screen, one-by-one
char ch;
while ((ch = fgetc(ptr)) != EOF)
    printf("%c", ch);

fputc()

fputc('A', ptr2);
fputc('!', ptr2);
// `cp` command: copy contents of ptr1 to ptr2
char ch;
while ((ch = fgetc(ptr)) != EOF)
    fputc(ch, ptr2);

fread()

// Read 10 integers from ptr into arr
int arr[10];
fread(arr, sizeof(int), 10, ptr);
// Store 80 doubles in a array of doubles size 80
double* arr2 = malloc(sizeof(double) * 80);
feead(arr2, sizeof(double), 80, ptr);
// Work like fgetc()
char c;
fread(&c, sizeof(char), 1, ptr);

fwrite()

// Write ten elements an array of ints size 10 into ptr
int arr[10];
fwrite(arr, sizeof(int), 10, ptr);
// Write 80 doubles from an array of 80 doubles into ptr
double* arr2 = malloc(sizeof(double) * 80);
fwrite(arr2, sizeof(double), 80, ptr);
// Work like fputc()
char c;
fwrite(&c, sizeof(char), 1, ptr);

Other Common Functions