Chp 12 File Input/Output Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Introduction of chp:

Why files are needed:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Data Organization:

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Operations that can be carried out on a file:

A
  1. Create a new file.
  2. Open existing file.
  3. Read a file.
  4. Write a file.
  5. Moving to a location in file (seeking).
  6. Close the file.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Function to open a file:
and how it works, what it does:
3 tasks.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why do we need buffer:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

FILE *fp;

what is this doing in the program of opening a file.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Reading from the file:

A

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().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Trouble opening in a file:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Closing the file:

A

fclose(fp);

Note it takes file pointer. This will remove file from buffer, now we can’t read it.
this functions does 3 things:

  1. The char in buffer would be written to file on disk.
  2. At end of file ASCII value 26 would get written.
  3. Buffer would be eliminated for memory.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

A file copy program:

Writing to a file:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

File opening modes:
Second argument in fopen():
6 modes, just mention them.

A
"r"
"w"
"a"
"r+"
"w+"
"a+"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

“r”

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 file not open returns NULL.

Operations possible:
reading from file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

“w”

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

“a”

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

“r+”

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 file not open returns NULL.

Operations possible:
reading existing contents, writing new contents, modifying existing contents of the file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

“w+”

A

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.

17
Q

“a+”

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.

18
Q

String (line) I/O Files:

their reading and writing:

A

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.

19
Q

The awkward new line:

A

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)

20
Q

Record I/O files:

how do you read/write any combination of data from/to file?

A

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.

21
Q

fflush( );

and why is it needed?

A

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.

22
Q

Text Files and binary files:

What are those 3 differences:

A

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.]

23
Q

Record I/O Revisited. State 2 disadvantages of previous mode:

A
  1. Number stored as strings would occupy more memory.

2. Number of field in structure if increased then using fprintf(), fscanf() hectic.

24
Q

Writing in binary mode:

reading in binary mode:

A

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.

25
Q

Data Management:

Deleting record:

A

First write all the records in a temporary file except for the record to be deleted, then delete original file and rename temp file back to original.

26
Q

functions clrscr(), gotoxy():

A

clrscr()
Clears content of the screen.
gotoxy(col,row)
Places the cursor to appropriate position on screen.

27
Q

Functions needed for deletion?

A

rewind() function:

remove(), rename()?
It makes the file pointer point the beginning of the file.
rewind( fp );
remove(“Emp.dat”) will delete file emp.dat.
rename(“Temp.dat”,”Emp.dat”) will rename temp.dat as emp.dat

28
Q

Data Management:

Role of the pointer to make this happen:

A

A pointer is initiated whenever we open a file.
On opening a file a pointer is set up which points to the first record in file.
This pointer resides in structure to which the file pointer in returned by fopen().
fread() reads the record where the pointer is placed and fwrite() writes there. On closing the file the pointer is deactivated.

29
Q

function to move pointer somewhere else?

A
function fseek():
fseek(fp, size, SEEK_CUR);
Lets us move pointer from one location to another,
size: offset to tell by how many byte should pointer move, if negative then backwards.
fp: file pointer.
SEEK_CUR : Move pointer with reference to current position.
SEEK_END: move pointer from end.
SEEK_SET: from beginning.
30
Q

is there any function to know pointer position?

A
function ftell() :
retuns a long int.
Tells where the pointer is positioned.
long int position = ftell(fp);
31
Q

How is data written in Low Level Disk I/O?

A

In low level disk I/O functions data can be written only as a buffer of bytes and not as chars or as strings or as formatted data.
It resembles fwrite() just the programmer must set up buffer for data, place the appropriate values in it before writing, and take them out after writing.

32
Q

Role of buffer in low-level Disk I/O :

A

Buffer is very much a part of program rather than being invisible as in high level disk I/O functions.

33
Q

A low level file copying program:

declaring buffer:

A

char buffer[520];

declare a character buffer. It’s size is imp for efficient operation, depends on OS.
This is the buffer in which data read from disk will be placed.

34
Q

Opening a file:

A

open(source, O_RDONLY|O_BINARY);
open takes two args:
1. filename.
2. opening mode.

35
Q

Opening mode O-flags:
everything about it:

7 modes

A

O_APPEND - Opens a file for appending.
O_CREAT - Creates a new file (no effect if exist)
O_RDONLY - Opens file for reading only.
O_WRONLY - or writing only.
O_RDWR - both read and write.
O_BINARY - creates a file in binary mode.
O_TEXT - Creates a file in text mode.

These O-flags are defined in the file “fcntl.h” so include it.
Notw low level doesn’t include “stdio.h”
When want to use 2 or more O-flags together use ‘|’ bitwise OR operator.
There is more to O_CREAT.

36
Q

When creating a new file how to use open:

A

open( target, O_CREAT|O_WRONLY, S_IWRITE);

creating needs one more argument in open, called PERMISSION argument.
S_IWRITE : Writing to the file permitted.
S_IREAD : Reading from file permitted.

these permissions can be used after including “types.h” and “stat.h” along with “fcntl.h”

37
Q

File handles:

A

open() returns an integer rather than a pointer.
This int is called file handle, number assigned to particular file.
if file not opened successfully then open() returns -1.

38
Q

Interaction between buffer and file: functions.

A
read() and write()
both take 3 arguments.
1. file handle
2. address of buffer.
3. max bytes to read/write.
read() returns no. of bytes read, int. at the end  buffer will be partially full and this number can help us keep track.

when using large buffer make them GLOBAL otherwise stack overflows.

39
Q

I/O Under Windows:

Why did it abandon Console I/O functions?

A

I/O in C is carried out using functions in library that comes with the C compiler targetted for specific OS.
Windows allow multiple apps to use same screen, so there’s a possibility that what’s written by one app to the console might get overwritten by the output of another app.
Hence windows abandoned Console I/O functions.
It uses a separate mechanism to send output to a window representing an application.

Still fprintf(), fscanf(), fread(), fwrite(), sprintf(), sscanf() work exactly same under windows.