Chp 12 File Input/Output Flashcards
Introduction of chp:
Why files are needed:
Memory is volatile, if data to display is large only Ltd can be stored and displayed, can’t be stored in memory as it would lost once program is terminated.
If same data needed again, should be entered through keyboard or regenerated programmatically?
Both are not feasible.
So its necessary to store the data in a manner that can be later retrieved and displayed either in part or whole. This medium is file on a disk.
Data Organization:
All data on the disk is stored in binary form.
The way its stored varies from OS to OS and it doesn’t affect the C programmer since he just has to the library functions for I/O.
Its compiler vendors responsibility to correctly implement these lib functions by taking help of OS>
Program –> Lib func –> OS –> Disk
Operations that can be carried out on a file:
- Create a new file.
- Open existing file.
- Read a file.
- Write a file.
- Moving to a location in file (seeking).
- Close the file.
Function to open a file:
and how it works, what it does:
3 tasks.
fopen( “filename.C”, “r”);
tells compiler we would be reading from this file, “r” is string, that’s why double quotes.
fopen() performs 3 imp tasks:
1. Searches on the disk for file.
2. Loads file from disk to a place in memory called buffer.
3. Sets up a character pointer that points to the first character in buffer.
Why do we need buffer:
If everytime to read a char from disk, it would take time for disk drive to position the read/write head correctly.
On floppy disk system, the drive motor has to actually start rotating the disk from standstill position everytime the disk is accessed.
This all takes long time. So its more sensible to read file contents in buffer then read the file char by char from buffer.
Even to write, write char on buffer then transfer to disk.
FILE *fp;
what is this doing in the program of opening a file.
FILE is a structure, defined in header file “stdio.h”.
TO be able to read a file, information like mode of opening, size, place from where next read operation would be performed,.. etc has to be maintained.
fopen() gathers all this info and stores in a structure ( FILE ). It returns address of this structure .
fp = fopen( “filename.C”, “r”);
fp is a structure pointer.
Reading from the file:
File’s open, in buffer, and a pointer points to the first char in buffer, this pointer is one of the elements of the structure FILE (fp pointing it).
ch = fgetc(fp);
fgetc() reads char from the current pointer position and then advances the pointer position to next char, it returns the char that’s read, here ch collected it.
A special char, ASCII value = 26, signifies end of file.
This char is inserted beyond last char in file when its created.
when fgetc() encounters this char it returns macro EOF (defined in “stdio.h”).
getc() is macro of fgetc().
Trouble opening in a file:
Maybe disk is damaged, or file is not created, or disk doesn’t have enough space to open a file or the disk is write protected… etc then the fopen() doesn’t open the file.
It instead returns NULL (in “stdio.h”: #define NULL 0).
so accordingly handle it in program, if fp == NULL print cant open and break.
Closing the file:
fclose(fp);
Note it takes file pointer. This will remove file from buffer, now we can’t read it.
this functions does 3 things:
- The char in buffer would be written to file on disk.
- At end of file ASCII value 26 would get written.
- Buffer would be eliminated for memory.
A file copy program:
Writing to a file:
fputc(ch, fp);
will write ch to fp. remember fp, fs are structure pointers.
to copy from s, ch = fgetc(fs);
This happens only for text files.
to copy files with .exe or .com, we need the files in binary mode.
File opening modes:
Second argument in fopen():
6 modes, just mention them.
"r" "w" "a" "r+" "w+" "a+"
“r”
Searches file. If file opened succesfully then loads it into memory and sets up a pointer which points to the first char in it.
If file not open returns NULL.
Operations possible:
reading from file.
“w”
Searches file. If file exits, its contents are overwritten. If it doesn’t exist, a new file is created.
If the file does not open returns NULL.
Operations possible:
Writing to the file.
“a”
Searches file.
If file opened succesfully then loads it into memory and sets up a pointer which points to the last char in it.
If it doesn’t exist, a new file is created.
If the file does not open returns NULL.
Operations possible:
Adding new contents at the end of the file.
“r+”
Searches file. If file opened succesfully then loads it into memory and sets up a pointer which points to the first char in it.
If file not open returns NULL.
Operations possible:
reading existing contents, writing new contents, modifying existing contents of the file.
“w+”
Searches file. If file exits, its contents are overwritten. If it doesn’t exist, a new file is created.
If the file does not open returns NULL.
Operations possible:
Writing new content, reading them back and modifying existing contents of the file.
“a+”
Searches file.
If file opened succesfully then loads it into memory and sets up a pointer which points to the first char in it.
If it doesn’t exist, a new file is created.
If the file does not open returns NULL.
Operations possible:
Reading existing contents, appending new contents to end of file. Cannot modify existing content.
String (line) I/O Files:
their reading and writing:
Reading or writing strings of char from and to files is also easy.
Here we use fputs to write and remember char s[80] will be ur string. fputs(s, fp); fputs(“\n”,fp);
as it does not automatically add newline char.
revise the program from book for reading and writing.
And use gets(s,79,fp) to read.
returns NULL when all lines have been read and we attempt to read one more line.
Takes 3 arg. 1st: address where string is stored, 2nd: max len of string so it doesn’t overflow array, 3rd: pointer to structure FILE.
The awkward new line:
when fputs() writes char”\n” it converts it to \r\n
When we read that using gets() \r\n is again converted to \n.
Its a feature of library but not of OS so OS will read \r and \n separately.
(remember \0 is present at the end of strings)
Record I/O files:
how do you read/write any combination of data from/to file?
We make structures and use
fprintf( fp, “FS”, e.name) and
fscanf( fp, “FS”, &e.name);
fp : FILE pointer e.name : Structure element.
FS : Format String &e.name : Address of element.
fflush( );
and why is it needed?
It is designed to remove or flush out any data remaining in the buffer.
It takes in argument, it must be buffer which we want to flush out.
stdin : buffer related with standard input device(keyboard)
scanf() assigns addresses the values and keeps the enter key unread in the keyboard buffer, which must be cleared.
Text Files and binary files:
What are those 3 differences:
Text files:
-filename.C ,
-opening mode “rt”, [By default it is text Mode} “r”.
-It has newline converted to carriage return-linefeed combination.
-Ends with ASCII char 26, to which read function returns EOF.
-Stores Numbers as strings of char so 1234 occupies 4 bytes and not 2 as normal int would.
only func to store no. fprintf().
Binary Files:
- Compiled version of program. ( .exe, .com).
- Opening Mode: “rb”,”wb”..
- \n will not be converted to anything.
- End Of file has no char associated with it, tracked from the number of char present in directory entry of file.
- Stores number in binary format [use fread(), fwrite()} so occupy same no. of bytes as it would in memory.
[ If you store numbers in binary mode, then u should read it in same mode again or else text mode on encountering 26 (hexadecimal : 1A) will prematurely end the file.]
Record I/O Revisited. State 2 disadvantages of previous mode:
- Number stored as strings would occupy more memory.
2. Number of field in structure if increased then using fprintf(), fscanf() hectic.
Writing in binary mode:
reading in binary mode:
we use fwrite()
it takes 4 arguments.
fwrite( &e, sizeof(e), 1 , fp);
1. &e : Address of structure to be written on disk.
2. sizeof(E) returns size of var in bytes, this helps to run the program even if elements in structure change.
3. Number of structures that we write in one time , in case of array of structure we would want more(entire array).
4. Pointer to the file we want to write.
For reading we use:
fread(&e, sizeof(e), 1, fp);
args same as above.
It causes the data read form disk to be placed in structure variable e, it also returns number of records read ( corresponds to what we asked, 1 here) .
When end of file reached, it returns 0 in that case.