C Language Tutorial
(Basic to Advanced)
File I/O
(Chapter 10)
# include<stdio.h>
intmain() {
FILE *fptr;
//Reading a file
char ch;
fptr = fopen("[Link]", "r");
if(fptr==NULL) {
printf("doesn't exist!\n");
} else {
fscanf(fptr,"%c", &ch);
printf("character in file is :%c\n",ch);
fscanf(fptr,"%c", &ch);
printf("character in file is :%c\n",ch);
fclose(fptr);
}
//Writing in a file
ch = 'M';
fptr = fopen("[Link]", "w");
fprintf(fptr, "%cANGO", ch);
fclose(fptr);
//fgets fptr = fopen("[Link]", "r");
printf("character in file is :%c\n",fgetc(fptr));
printf("character in file is :%c\n",fgetc(fptr));
printf("character in file is :%c\n",fgetc(fptr));
printf("character in file is :%c\n",fgetc(fptr));
printf("character in file is :%c\n",fgetc(fptr));
fclose(fptr);
//fputc fptr =
fopen("[Link]", "w");
fputc('a', fptr); fputc('p', fptr);
fputc('p', fptr); fputc('l', fptr);
fputc('e', fptr); fclose(fptr);
//read the full file (EOF)
fptr = fopen("[Link]", "r");
ch = fgetc(fptr);
while(ch!=EOF) {
printf("%c", ch);
ch = fgetc(fptr);
} printf("\n");
fclose(fptr);
return 0;
}