File management in C involves operations like creating, opening, reading, writing, and closing files. C provides several functions through the stdio.h
library for these tasks.
FILE *
):A FILE *
is a pointer to a file object used for all file operations.
Example:
FILE *fp;
Use fopen()
to open a file.
FILE *fopen(const char *filename, const char *mode);
"r"
: Read (file must exist)."w"
: Write (creates a new file or truncates an existing one)."a"
: Append (writes at the end of the file, creates if not existing)."r+"
: Read and write."w+"
: Write and read (truncates existing file)."a+"
: Append and read.Example:
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Error opening file\\\\n");
}
Use fclose()
to close a file after completing operations.
fclose(fp);
fgetc()
: Reads a single character.
char ch = fgetc(fp);
fgets()
: Reads a string from the file.
char str[100];
fgets(str, 100, fp);
fscanf()
: Reads formatted input (similar to scanf()
).
int num;
fscanf(fp, "%d", &num);
fputc()
: Writes a single character.
fputc('A', fp);