Files

File Structure in C

  • Files are continuous sequences of bytes ending with an EOF (End Of File) indicator.

  • Current position denotes where read/write operations occur.

  • Files can be in text or binary format.

File Handling Functions

Opening a File:

FILE *fopen(const char* restrict name, const char *restrict mode);

Renaming a File:

int rename(const char *oldname, const char *newname);

Closing a File:

int fclose(FILE *filePtr);

Deleting a File:

int remove(const char* filename);

Reading Characters from a File:

Reading Strings from a File:

Reading Formatted Input:

Writing Characters to a File:

Writing Strings to a File:

Writing Formatted Output:

Miscellaneous Functions:

  • Checking for end of file: int feof(FILE *filePtr);

  • Flushing data to file: int fflush(FILE *filePtr);

  • Get current file position: int fgetpos(FILE *stream, fpos_t *pos);

  • Set file position: int fseek(FILE *stream, long int offset, int whence);

  • Get current position in file: long ftell(FILE *stream);

Example of Repositioning File Stream:

Using fseek(), you can move the file pointer to a desired location.

Writing/Reading Integers:

Use putw() to write and getw() to read.

Flushing a File:

fflush() flushes the output buffer of a file stream.