



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




















1. Briefly explain the pre-processor directives in detail.
Ans:
As the name suggests Preprocessors are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C.
You can see the intermediate steps in the above diagram. The source code written by programmers is stored in the file program.c. This file is then processed by preprocessors and an expanded source code file is generated named program. This expanded file is compiled by the compiler and an object code file is generated named program .obj. Finally, the linker links this object code file to the object code of the library functions to generate the executable file program.exe.
Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the source code before compiling. All of these preprocessor directives begin with a „#‟ (hash) symbol. This („#‟) symbol at the beginning of a statement in a C program indicates that it is a pre- processor directive. We can place these preprocessor directives anywhere in our program
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef. Files: Text and Binary files, Creating and Reading and writing text and binary files, Appending data to existing files, Writing and reading structures using binary files, Random access using fseek, ftell and rewind functions.
There are 3 main types of preprocessor directives:
a) Header File or Standard Functions: These files contains definition of pre-defined functions like printf(), scanf() etc. These files must be included for working with these functions. Different function are declared in different header files. For example standard I/O functions are in „stdio.h‟ file whereas functions which perform string operations are in „string‟ file. Syntax:
#include< file_name > where file_name is the name of file to be included. The „<„ and „>‟ brackets tells the compiler to look for the file in standard directory.
b) User defined header files: When a program becomes very large, it is good practice to divide it into smaller files and include whenever needed. These types of files are user defined files. These files can be included as:
#include" filename "
2. Macros : Macros are a piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The „#define‟ directive is used to define a macro. Let us now understand the macro definition with the help of a program: #include // macro definition #define LIMIT 5 int main() { for (int i = 0; i < LIMIT; i++) { printf("%d \n",i); }
printf("%f",PI); } Output: Compile Time Error: 'PI' undeclared
b). #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.
Syntax:
#ifdef MACRO //code #endif
c) #ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.
Syntax:
#ifndef MACRO //code #endif
d). #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code.
Syntax:
#if expression //code #endif
e) #else
The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
#if expression //if code #else //else code #endif
Syntax with #elif
#if expression //if code #elif expression //elif code #else //else code #endif
Example
#include #include #define NUMBER 1 void main() { #if NUMBER== printf("Value of Number is: %d",NUMBER); #else print("Value of Number is non-zero"); #endif getch(); } Output: Value of Number is non-zero
3. Explain different modes of opening files with syntax and example? Ans: To store data in a file three things have to be specified for operating system. They include 1. FILENAME : It is a string of characters that make up a valid file name which may contain two parts,a primary name and an optional period with the extension. Prog1.c Myfirst.java Data.txt store 2. DATA STRUCTURE: It is defined as FILE in the library of standard I/O function definitions. Therefore all files are declared as type FILE.FILE is a define data type. FILE *fp; 3. PURPOSE: It defines the reason for which a file is opened and the mode does this job. fp=fopen(“filename”,”mode”); The different modes of opening files are : “r” (read) mode: The read mode (r) opens an existing file for reading. When a file is opened in this mode, the file marker or pointer is positioned at the beginning of the file (first character).The file must already exist: if it does not exist a NULL is returned as an error. If we try to write a file opened in read mode, an error occurs. Syntax: fp=fopen (“filename”,”r”);
“w” (write) mode The write mode (w) opens a file for writing. If the file doesn‟t exist, it is created. If it already exists, it is opened and all its data is erased; the file pointer is positioned at the beginning of the file It gives an error if we try to read from a file opened in write mode. Syntax: fp=fopen (“filename”,”w”);
“a” (append) mode
The append mode (a) opens an existing file for writing instead of creating a new file. However, the writing starts after the last character in the existing file ,that is new data is added, or appended, at the end of the file. If the file doesn‟t exist, new file is created and opened. In this case, the writing will start at the beginning of the file.
Syntax: fp=fopen (“filename”,”a”);
“r+” (read and write) mode
In this mode file is opened for both reading and writing the data. If a file does not exist then NULL, is returned.
Syntax: fp=fopen (“filename”,”r+”);
“w+” (read and write) mode
In this mode file is opened for both writing and reading the data. If a file already exists its contents are erased and if a file does not exist then a new file is created.
Syntax: fp=fopen (“filename”,”w+”);
“a+” (append and read) mode
In this mode file is opened for reading the data as well as data can be added at the end.
Syntax: fp=fopen (“filename”, “a+”);
Figure : File Opening Modes
NOTE: To perform operations on binary files the following modes are applicable with an extension b like rb,wb,ab,r+b,w+b,a+b,which has the same menaing but allows to perform operations on binary files.
fp=fopen (“filename”,”mode”); //statement to open file. Here FILE is a data structure defined for files. fp is a pointer to data type FILE. filename is the name of the file. mode tells the purpose of opening this file. Reading data from file : Input functions used are ( Input operations on files) a) getc(); It is used to read characters from file that has been opened for read operation. Syntax: c=getc (file pointer) This statement reads a character from file pointed to by file pointer and assign to c. It returns an end-of-file marker EOF, when end of file has been reached b) fscanf(); This function is similar to that of scanf function except that it works on files. Syntax: fscanf (fp, ”control string”, list); Example fscanf(f1,”%s%d”,str,&num); The above statement reads string type data and integer type data from file. c) getw(); This function reads an integer from file. Syntax: getw (file pointer); d) fgets(): This function reads a string from a file pointed by a file pointer. It also copies the string to a memory location referred by an array. Syntax: fgets(string,no of bytes,filepointer); e) fread(): This function is used for reading an entire structure block from a given file. Syntax: fread(&struct_name,sizeof(struct_name),1,filepointer); Writing data to a file: To write into a file, following C functions are used a. putc(): This function writes a character to a file that has been opened in write mode. Syntax: putc(c,fp); This statement writes the character contained in character variable c into a file whose pointer is fp. b. fprintf(): This function performs function, similar to that of printf. Syntax: fprintf(f1,”%s,%d”,str,num); c. putw(): It writes an integer to a file. Syntax: putw (variable, fp); d. fputs(): This function writes a string into a file pointed by a file pointer. Synatax: fputs(string, filepointer); e. fwrite(): This function is used for writing an entire block structure to a given file. Syntax: fwrite(&struct_name, sizeof(struct_name),1,filepointer);
Closing a file: A file is closed as soon as all operations on it have been completed.Closing a file ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. Another instance where we have to close a file is to reopen the same file in a different mode. Library function for closing a file is Syntax: fclose(file pointer); Example: fclose(fp); Where fp is the file pointer returned by the call to fopen(). fclose() returns 0 on success (or) - 1 on error. Once a file is closed, its file pointer can be reused for another file. Note: fcloseall() can be used to close all the opened files at once.
5. What are the file I/O functions in C. Give a brief note about the task performed by each function? Ans: In order to perform the file operations in C we must use the high level I/O functions which are in C standard I/O library. They are i) getc() and putc() functions: getc()/fgetc() : It is used to read a character from a file that has been opened in a read mode. It reads a character from the file whose file pointer is fp. The file pointer moves by one character for every operation of getc(). The getc() will return an end-of – marker EOF, when an end of file has been reached. Syntax: getc(fp); Ex: char ch; ch=getc(fp); putc()/fputc() -: It is used to write a character contained in the character variable to the file associated with the FILE pointer fp. fputc() also returns an end-of – marker EOF, when an end of file has been reached. Syntax: putc(c,fp); Example: char c; putc(c,fp); Program using fgetc() and fputc(): #include void main() { FILE *fp;
FILE f3; f3=fopen("mynew3","w"); fprintf(f3,"%d %s %f",a,s1,c); fclose(f3); f3=fopen("mynew3","r"); fscanf(f3,"%d %s %f",&b,s2,&d); printf("\n a=%d \t s1=%s \t c=%f \n b=%d \t s2=%s \t d=%f",a,s1,c,b,s2,d); fclose(f3); } iii) getw() and putw(): The getw() and putw()are integer oriented functions .They are similar to the getc() and putc() functions and are used to read and write integer values. These functions would be useful when we deal with only integer data. The general form of getw() and putw() are Syntax: putw(integer,fp); Syntax: getw(fp); Program using getw() and putw(): /Printing odd numbers in odd file and even numbers in even file/ #include void main() { int x,i; FILE f1,fo,fe;//creating a file pointer f1=fopen("anil.txt","w"); //opening a file printf("\n enter some numbers into file or -1 to stop \n"); for(i=0;i<20;i++) { scanf("%d",&x); if(x== -1)break; putw(x,f1); //writing read number into anil.txt file one at a time } fclose(f1); //closing a file opened for writing input printf("\n OUTPUT DATA\n"); f1=fopen("anil.txt","r");//open anil in read mode to read data fo=fopen("odd3f","w");
fe=fopen("even3f","w"); while((x=getw(f1))!=EOF) { printf("%d\t",x); if(x%2==0) putw(x,fe); else putw(x,fo); } fcloseall(); fo=fopen("odd3f","r"); printf("\n contents of odd file are :\n"); while((x=getw(fo) )!= EOF) printf(" %d\t",x); fe=fopen("even3f","r"); printf("\n contents of even file are :\n"); while((x=getw(fe)) != EOF) printf(" %d\t",x); fcloseall(); } iv) fputs() and fgets(): fgets(): It is used to read a string from a file pointed by file pointer. It copies the string to a memory location referred by an array. Syntax:fgets(string,length,filepointer); Example: fgets(text,50,fp1); fputs(): It is used to write a string to an opened file pointed by file pointer. Syntax: fputs(string,filepointer); Example: fputs(text,fp);
Program using fgets() and fputs(): #include void main() { FILE *fp; char str[50];
printf("\n Enter details of player name ,age and runs scored :\n "); fflush(stdin); scanf("%s %d %d",p1.pname,&p1.age,&p1.runs); fwrite(&p1,sizeof(p1),1,f3); fclose(f3); f3=fopen("player.txt","r"); fread(&p2,sizeof(p2),1,f3); fflush(stdout); printf("\nPLAYERNAME:=%s\tAGE:=%d\tRUNS:=%d ",p2.pname,p2.age,p2.runs); fclose(f3); }
6. Explain about random access to files with example? Ans: At times we needed to access only a particular part of a file rather than accessing all the data sequentially, which can be achieved with the help of functions fseek, ftell and rewind available in IO library. ftell() :- ftell takes a file pointer and returns a number of type long, that corresponds to the current position. This function is useful in saving the current position of the file, which can later be used in the program. Syntax : n =ftell(fp); n would give the Relative offset (In bytes) of the current position. This means that already n bytes have a been read or written rewind():- It takes a file pointer and resets the position to the start of the file. Syntax: rewind(fp); n=ftell(fp); would assign 0 to n because the file position has been set to start of the file by rewind(). The first byte in the file is numbered 0, second as 1, so on. This function helps in reading the file more than once, without having to close and open the file. Whenever a file is opened for reading or writing a rewind is done implicitly. fseek:- fseek function is used to move the file pointer to a desired location within the file. Syntax: fseek(file ptr,offset,position);
file pointer is a pointer to the file concerned, offset is a number or variable of type long and position is an integer number which takes one of the following values. The offset specifies the number of positions( Bytes ) to be moved from the location specified by the position which can be positive implies moving forward and negative implies moving backwards. POSITION VALUE VALUE CONSTANT MEANING 0 SEEK_SET BEGINNING OF FILE 1 SEEK_CUR CURRENT POSITION 2 SEEK_END END OF FILE
Example: fseek(fp,10,0) ; fseek(fp,10,SEEK_SET); // file pointer is repositioned in the forward direction 10 bytes. fseek(fp,-10,SEEK_END); // reads from backward direction from the end of file. When the operation is successful fseek returns 0 and when we attempt to move a file beyond boundaries fseek returns -1. Some of the Operations of fseek function are as follows:
STATEMENT MEANING fseek(fp,0L,0); Go to beginning similar to rewind() fseek(fp,0L,1); Stay at current position fseek(fp,0L,2); Go to the end of file, past the last character of the file. fseek(fp,m,0); Move to (m+1)th^ byte in the file. fseek(fp,m,1); Go forward by m bytes fseek(fp,-m,1); Go backwards by m bytes from the current position fseek(fp,-m,2); Go backwards by m bytes from the end.(positions the file to the mth character from the end)
Program on random access to files: #include void main() { FILE *fp; char ch; fp=fopen("my1.txt","r"); fseek(fp,21,SEEK_SET);
pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing. It returns zero otherwise. The statement if(ferror(fp)! =0) printf(“an error has occurred\n”); would print an error message if the reading is not successful c). fp==null: We know that whenever a file is opened using fopen function, a file pointer is returned. If the file cannot be opened for some reason, then the function returns a null pointer. This facility can be used to test whether a file has been opened or not. Example if(fp==NULL) printf(“File could not be opened.\n”); d) perror(): It is a standard library function which prints the error messages specified by the compiler. For example: if(ferror(fp)) perror(filename);
Program for error handling in files: #include
void main() { FILE *fp; char ch; fp=fopen("my1.txt","r"); if(fp==NULL) printf(“\n file cannot be opened”); while(!feof(fp)) { ch=getc(fp); if(ferror(fp)) perror(“problem in the file”); else
putchar(ch); } fclose(fp); }
8. Write a c program to read and display the contents of a file? Ans: Program: #include void main() { FILE *f1; char ch; f1=fopen("data.txt","w"); printf("\n enter some text here and press cntrl D or Z to stop :\n"); while((ch=getchar())!=EOF) fputc(ch,f1); fclose(f1); printf(“\n the contents of file are \n:”); f1 = fopen(“data.txt”,"r"); while( ( ch = fgetc(f1) ) != EOF ) putchar(ch); fclose(f1); } 9. Write a c program to copy the contents of one file to another? Ans: Program: #include void main() { FILE f1,f2; char ch; f1=fopen("mynew2.txt","w"); printf("\n enter some text here and press cntrl D or Z to stop :\n"); while((ch=getchar())!=EOF) fputc(ch,f1); fclose(f1); f1=fopen("mynew2.txt","r"); f2=fopen("dupmynew2.txt","w"); while((ch=getc(f1))!=EOF)