You are on page 1of 48

Unit 5

Topics
File processing C Preprocessor Conditional compilation Low Level Programming Calling BIOS-DOS interrupt CMOS Keyboard and Speaker Writing into the Video Buffer

File
Collection of related records kept together.

C File Processing
File processing consists of creating, storing, and/or retrieving, the contents of a file to or from a recognizable medium.
For example, it is used to save word processed files to a hard drive, to store a presentation on floppy disk, or to open a file from a CD-ROM.

File Operations (system calls related to files)


Create Delete Open Close Read Write Append Seek Rename

FILE is a structure and it is defined in the stdio.h header file. It provides the filename to the operating system. This FILE structure contains all the information being used such as size, location in memory etc.. First declare an instance of the FILE structure. Here is an example: FILE *fp; Fp is a pointer variable which contains address of the structure FILE. When a file is opened, a pointer points to the first character.

Opening and/or Saving Files


To create a new file, open an existing file, or save a file, you use the fopen() function. Its syntax is: FILE *fopen(const char *FileName, const char *Mode); Eg. Fp =fopen(filename,w); The first argument, FileName, must be a valid name of a file. If the user is opening an existing file, you can make sure the file really exists, retrieve its name and pass it to the fopen() function. fopen() function is used to save a new file, to open an existing one, or to save a file that was only modified, The second argument, Mode, actually allows you to decide.

If a file is unable to open, it returns NULL. R Opens an existing file for reading only W Saves a new file if does not exist, if exist content are over written. A if file exists, the pointer points to the first character in the file. If not, a new file is created. r+ if file exits it loads into the memory. Reading, writing and modification are possible. w+ Saves a new file if does not exist, if exist content are over written. a+ Creates a new file or modifies an existing one.

Closing a file
After using a file, you should/must close its stream. This is done using the fclose() function. Its syntax is: int fclose(FILE *stream); Ex. fclose(fp);

Writing Data to a File


To save a file, you must write data to its contents. This operation is performed using the fprintf() or the fwprintf() functions. Their syntaxes are: int fprintf(FILE *stream, const char *format, ...); int fwprintf(FILE *stream, const wchar_t *format, ...); The fprintf() function takes a few arguments depending on how it is used. The first parameter, stream, must be an instance of a FILE structure. The second parameter, format, is a string that specifies how data will be formatted and possibly positioned in the stream instance.

File operations
fprintf() is a function which writes values of variables to the file.
Fscanf() is a function which reads values from a file specified by the FILE pointer. Fflush() clears the buffer related to its argument. Fread() function reads information from the file. Used for binary I/O. Fwrite() function writes information to the file. Used for binary I/O. rewind(fp) function places the pointer to the beginning of the file. Remove(fp) function deletes the specified files. Rename(fp) function changes the file name

the location of the file pointer from the beginning of the file. feof() this function is used to test whether the pointer is at EOF or not. It returns 1 if the file pointer is at the EOF, else return 0. fpurge() function is used to clear the buffers of unwritten or unread data that is in a buffer waiting. fseek() function is used to move the file position to a desired location within the file. ftell() function returns used to test whether the file pointer is at EOF or not. ferror() function tests the error indicator for the file pointes by the pointer.

fwrite and fread function General format


int fwrite(void *ptr, size_t size,size_t nmemb, FILE *fp1); ptr = ptr is from where we are reading size = total number of bytes for the specified data type nmemb = number of elements to be read. fp1 = location where to write. int fread(void *ptr, size_t size,size_t nmemb, FILE *fp1); ptr = ptr is the location where we are storing size = total number of bytes for the specified data type nmemb = number of elements to be read. fp1 = location where we are reading.

Example
Int x[5]={10,20,30,40,50}; FILE *fp1; Fwrite(&x,sizeof(int),5,fp1); Int x; fread(&x,sizeof(int),1,fp1); printf(%d,x);

Fseek function General format Fseek(fileptr,offset,position); fileptr is pointer to a file. offset a number or variable of type long. It specifies the number of positions (bytes) to be moved from the location specified by the position. position integer number. It can take 3 values 0 - beginning of the file 1 current position 2 end of the file.

Other I/O
Getchar() reads input from the keyboard one character at a time. putchar() writes input to the screen one character at a time. Getc() - reads input from the file specified one character at a time. putc() writes input to the file specified one character at a time. C=getchar() Putc(c,fp); - puts each character to the file. Getc(fp) reads one character at a time from a file

Write a program to read input character by character using getc() and opens a file and writes them into it. Read the content from the same file using fgetc() and display on the screen.

#include <stdio.h> Int main() { file *fp1; fp1 = fopen(f1,w); While ((c=getchar())!=EOF) putc(c,fp1); Fclose(fp1); Fp1=fopen(f1,r); while((c=getc(fp1))!=EOF) printf(%c,c); fclose(fp1); Return 0; }

File checking I if(fp==0) { fprintf(Cannot open source file) exit(); } II while ((ch=getc(fp))!=EOF) { printf(%c,ch); } While(fread(&b,sizeof(b),1,fp)!=eof())

C Preprocessor

Conditional Compilation
Controls the execution of preprocessor directives & compilation of code
Define NULL, if it hasnt been defined yet
#if !defined(NULL) #define NULL 0 #endif

Use to comment out code (for comments)


#if 0 code prevented from compiling #endif

Preprocessor Directives
#define for symbolic constants
#define identifier text
Creates symbolic constants The identifier is replaced by text in the program

Example #define PI 3.14 area = PI * radius * radius;


Replaced by area = 3.14 * radius * radius by preprocessor before compilation

Predefined Symbolic Constants


#include <stdio.h> int main(){ printf("%d\n%s\n%s\n%s\n", __LINE__, __FILE__, __DATE__, __TIME__); }

Output:
3 example.c Oct 13 2003 19:27:57

line #, file name, compiled date, compiled time

Preprocessor Directives
#define for macros
#define macro-identifier text
Can have arguments The macro is expanded in the program

Example #define AREA(x) ( (PI) * (x) * (x)) circle_area = AREA(5);


Expanded to circle_area = ((3.14)*(5)*(5)) by preprocessor before compilation

Command Line Arguments


Command line arguments are the whitespace seperated tokens given in the command prompt (or shell prompt ) along with the program name. Eg. cat foo bar cat is the file name Foo is the first argument Bar is the second argument This command line arguments are passed to the main() function arguments

Command Line Arguments (1)


int main(int argc, char* argv[]) argc
Number of arguments (including program name)

argv
Array of char*s (that is, an array of c strings) argv[0]: = program name argv[1]: = first argument argv[argc-1]: last argument

Command Line Arguments (2)


#include <stdio.h> int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n", i, argv[i]); return 0; }

Write a program which takes a set of numbers (integers) along the command line and prints its average.
#include <stdio.h> #include <stdlib.h> Int main(int argc, char *argv[]) { int I, sum=0; float avg; For(i=1;i<argc;i++) { sum = sum + atoi(argv[i]); } Avg = sum/(arc-1); Printf(Average : %f, avg); Return 0; }

File copy using CLA


txtcpy one.txt two.txt #include <stdio.h> int main(int argc, char **argv) { FILE *fp1, *fp2; int key; if (argc < 3) { puts(Sorry, we need minimum 3 arguments"); return 0; } if ((fp1 = fopen(argv[1], "r")) == NULL) { puts("Unable to open the file to be copied"); return 0; }

if ((fp2 = fopen(argv[2], "w")) == NULL) { puts("Unable to open the output file"); return 0; } while (!feof(fp1)) { key = fgetc(fp1); if (!feof(fp1)) fputc(key, fp2); } fclose(fp1); fclose(fp2); return 0; }

Low-level language in C
A programming language that is very close to machine language. All assembly languages are low-level languages. A machine language or an assembly language. Low-level languages are closer to the hardware than are high-level programming. A low-level language does not need a compiler or interpreter to run;

Low-level programming languages are sometimes divided into two categories: first generation, and second generation. First generation The first-generation programming language, or 1GL, is machine code. It is the only language a microprocessor can process directly without a previous transformation. Currently, programmers almost never write programs directly in machine code, because it requires attention to numerous details which a high-level language would handle automatically, and also requires memorizing or looking up numerical codes for every instruction that is used. For this reason, second generation programming languages provide one abstraction level on top of the machine code. Example: A function in 32-bit x86 machine code to calculate the nth Fibonacci number:
8B542408 83FA0077 06B80000 0000C383 FA027706 B8010000 00C353BB 01000000 B9010000 008D0419 83FA0376 078BD98B C84AEBF1 5BC3

Second generation The second-generation programming language, or 2GL, is assembly language. It is considered a secondgeneration language because while it is not a microprocessor's native language, an assembly language programmer must still understand the microprocessor's unique architecture (such as its registers and instructions). These simple instructions are then assembled directly into machine code. The assembly code can also be abstracted to another layer in a similar manner as machine code is abstracted into assembly code. Example: The same Fibonacci number calculator as above, but in x86 assembly language using MASM syntax:

fib:
mov edx, [esp+8] cmp edx, 0 ja @f mov eax, 0 ret @@: cmp edx, 2 ja @f mov eax, 1 ret @@: push ebx mov ebx, 1 mov ecx, 1 @@: lea eax, [ebx+ecx] cmp edx, 3 jbe @f mov ebx, ecx mov ecx, eax dec edx jmp @b @@: pop ebx ret

Calling BIOS-DOS interrupt


Interrupt definition an interrupt is a signal to the microprocessor which when generated asks the microprocessor to stop its job and execute some other task. Software interrupt
Int86() library function in C generates a software interrupt.

Hardware interrupt
Hitting a key from the keyboard.

Every interrupt has its own number 8086 processor supports 256 interrupts. Interrupt Service Routine (ISR)
Small memory resident routine which is executed when an interrupt occur. The address of ISRs are stored in Interrupt Vector Table (IVT).

Int86()
To find the memory size Positioning the cursor on the screen

syntax Int86(16,&inregs,&outregs); Has 3 arguments


Interrupt number Two union variables.

BIOS/DOS services
Deleting a file Creating directories Reading disk sector

Intdos()
This functions call the DOS services gathered under interrupt number 0X21. This function is used to delete a file. Int86x() and intdosx() to invoke ROM-BIOS and DOS service respectively. These functions is used to read disk sectors and creating directories.

CMOS
Complementary metaloxidesemiconductor (CMOS) ( "sea moss"), is a major class of integrated circuits. Nonvolatile BIOS memory refers to a small memory on PC motherboards that is used to store BIOS settings. It was traditionally called CMOS RAM which has a small battery that provides power. CMOS chips pass information to the BIOS (Basic Input/Output System) when the computer is turned on (called bootup). CMOS stores information such as boot order (the order the computer looks for information, such as A drive first, C drive second, and so on), real-time system clock, calendar settings, hardware passwords, hard drive configuration settings, and the installed memory (RAM). Essentially the CMOS chip stores data for the BIOS so that a computer can boot up properly.

Keyboard and speaker


keyboard is an input device, partially modeled after the typewriter keyboard, which uses an arrangement of buttons or keys.

Video buffer
A storage location in a system or video cards memory that holds information before it is sent to the display device. Some computer BIOS setups may allow the user to 'Enable' or 'Disable' the Video buffer.

Writing into video buffer


To write directly to VDU memory, one must first know the address of the beginning of the VDU memory block. Beginning addres are
F MA(Monochrome Adapter) 0 X B000000L CGA (Colour Graphics Adapter) 0 X B8000000L

Each character present on the screen has two bytes in VDU memory. The first byte contains the ASCII value of the character Next byte contains the attribute (colour) of the character. Ex. Using CGA. if A is displayed in 0th row, 0th col on the screen, then address 0XB8000000L contains the ASCII value of A and address (0XB8000000L +1) contains attribute of A.

One full screen needs 4000 bytes (80 X 25 X 2). Program to write entire screen with As by writing them directly into VDU memory. Main() { int I; char far *vidmem = (char far *) 0 X B8000000L; For (i=0;i<=3999;i=i+2) *(vidmem+i) = A; }

You might also like