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:
int fgetc(FILE *filePtr);
int getc(FILE *filePtr);
Reading Strings from a File:
char *fgets(char *str, int nchars, FILE *stream);
Reading Formatted Input:
int fscanf(FILE *stream, const char *format, ...);
Writing Characters to a File:
int fputc(int c, FILE *filePtr);
int putc(int c, FILE *filePtr);
Writing Strings to a File:
int fputs(const char *str, FILE *stream);
Writing Formatted Output:
int fprintf(FILE *stream, const char *format, ...);
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.