FILE Open Read Write Seek
A C console program that copies a file two ways — character at a time with fscanf, then in 512-byte buffered chunks after seeking back to the start.
A compact demonstration of the C runtime file functions on Windows: fopen in binary mode ("rb"/"wb"), reading and writing one character at a time with fscanf/fprintf, rewinding with fseek, and then copying the same file much faster using fread/fwrite in 512-byte blocks. It is a good reference for when you want to see the classic open-copy-seek-close pattern without any Win32 CreateFile ceremony - the buffered loop's while(BufferSize == MaxBuffer) idiom is the standard way to detect the final partial block.
#include <windows.h>
#include <stdio.h>
#define MaxBuffer 512
int main()
{
FILE *LocalSource;
FILE *LocalTarget;
char *SourceName = "C:/Windows/Desktop/Source.Txt";
char *TargetName = "C:/Windows/Desktop/Target.Txt";
char Buffer[MaxBuffer+1];
char CharBuffer = '\0';
int End_Of_File = 0;
int BufferSize = 0;
/* Open File For Binary Read */
if((LocalSource = fopen(SourceName,"rb")) == NULL)
{
printf("Could Not Open %s For Read.",SourceName);
return 0;
}
/* Open File For Binary Write */
if((LocalTarget = fopen(TargetName,"wb")) == NULL)
{
printf("Could Not Open %s For Write.",TargetName);
return 0;
}
/* Write Source File To Target File One Character At A Time */
while (End_Of_File != EOF)
{
End_Of_File = fscanf(LocalSource, "%c", &CharBuffer);
if (End_Of_File != EOF)
{
fprintf(LocalTarget, "%c", CharBuffer);
}
}
// SEEK_SET 0 File beginning
// SEEK_CUR 1 Current file pointer position
// SEEK_END 2 End-of-file
/* Seek To Beginning Of File */
fseek(LocalSource, 0L, SEEK_SET);
/* Write Source File To Target File One Buffer At A Time */
do
{
BufferSize = fread(Buffer, sizeof(char), MaxBuffer, LocalSource);
fwrite(Buffer, sizeof(char), BufferSize, LocalTarget);
}
while(BufferSize == MaxBuffer);
if(LocalSource) fclose(LocalSource);
if(LocalTarget) fclose(LocalTarget);
return 0;
}
The comment block before the fseek call doubles as a quick reference for the three seek origins: SEEK_SET (beginning), SEEK_CUR (current position), and SEEK_END (end of file).