File I/O Flashcards
types of memory storage
RAM -random access memory-volatile
if power is interupted then it’s data or any changes made is lost
contents are lost when program terminates.
harddisk-non-volatile means if power is interrupted data or changes made is not lost
a program is run in RAM and it has to access some file stored in harddisk it is done by File I/O which can be done using C also.
files are used to persist the data
Operations on Files
create a file
open a file
close a file
read a file
write a file
Types of Files
Text Files
-textual data
-.txt,.c
Binary Files
-binary data
-.exe,.mp3.jpg
File pointers
FILE is a structure that needs to be created before opening a file
a FILE ptr points to this structure and is used to access this file
FILE *fptr;
Open and Close a file
Opening a file
FILE *fptr;
fptr=fopen(“file name”,mode);
mode=
“r”-read
“rb”-read in binary
“w”-write
“wb”-write in binary
“a”-append
Closing a file
fclose(fptr);
if a file doesn’t exist and we try to read it then the pointer will show null
if a file doesn’t exist and we try to write it that file is created
Read from a file
char ch;
fscanf(fptr,”%c”,&ch);
printf(“%c”,ch);
write to a file
after switching to write mode
char ch=”a”;
fprintf(fptr,”%c”,ch);
we can also append files
Read and write using special functions
fgetc(fptr)-read character
fputc(‘A’,fptr)-put character into file
both of these code serves the same purpose
fscanf(fptr,”%c”,&ch);
printf(“%c\n”,fgetc(fptr));
fprintf(fptr,”%c”,ch);
fputc(‘a’,fptr);
this is only for characters
EOF
EOF -End of file
fgetc returns EOF to show that the file has ended
char ch;
ch=fgetc(fptr);
while (ch!=EOF)
{
printf(“%c”,ch);
ch=fgetc(fptr);
}
printf(“\n”);
}