FILE HANDLING IN C - DETAILED NOTES
1. Introduction
A file is a collection of data stored on a secondary storage device. File handling allows permanent
storage of data.
2. File Pointer
FILE *fp; is used to declare a file pointer.
3. Opening a File
fp = fopen("[Link]", "r");
Modes: r (read), w (write), a (append), r+, w+, a+
4. Closing a File
fclose(fp);
5. Writing to a File
fprintf(fp, "Hello World");
fputc('A', fp);
fputs("Hello", fp);
6. Reading from a File
fscanf(fp, "%s", str);
fgetc(fp);
fgets(str, 100, fp);
7. Example Program
#include
int main(){
FILE *fp;
char ch;
fp=fopen("[Link]","w");
fprintf(fp,"Hello");
fclose(fp);
fp=fopen("[Link]","r");
while((ch=fgetc(fp))!=EOF){printf("%c",ch);}
fclose(fp);
}
8. Random Access
fseek(fp, offset, SEEK_SET);
ftell(fp);
rewind(fp);
9. Key Points
Always check if file opened successfully.
Close file after use.
Use correct mode.