Pps Unit3 Qa
Pps Unit3 Qa
A program which processes the source code before it passes through the compiler is known as
preprocessor.
The commands of the preprocessor are known as preprocessor directives.
It is placed before the main().
It begins with a # symbol.
They are never terminated with a semicolon.
Preprocessor Directives
The preprocessor directives are divided into four different categories which are as follows:
1. Macro expansion
There are two types of macros - one which takes the argument and another which does not take any
argument.
Values are passed so that we can use the same macro for a wide range of values.
Syntax:
#define name replacement text
Where,
name – it is known as the micro template.
replacement text – it is known as the macro expansion.
2. File inclusion
The file inclusion uses the #include.
Syntax:
#include filename
The content that is included in the filename will be replaced at the point where the directive is
written.
By using the file inclusive directive, we can include the header files in the programs.
Macros, function declarations, declaration of the external variables can all be combined in the header
file instead of repeating them in each of the program.
The stdio.h header file contains the function declarations and all the information regarding the input
and output.
If the first way is used, the file and then the filename in the current working directory and the
specified list of directories would be searched.
If the second way, is used the file and then the filename in the specified list of directories would be
searched.
3. Conditional compilation
The conditional compilation is used when we want certain lines of code to be compiled or not.
It uses directives like #if, #elif, #else, #endif
Syntax
#if TEST <= 5
statement 1;
statement 2;
#else
statement 3;
statement 4;
#endif
If there are a number of conditions to be checked we can use the #elif instead of #else and #if.
4. Miscellaneous directive
There are some directives which do not fall in any of the above mentioned categories.
Create a File
Whenever you want to work with a file, the first step is to create a file. A file is nothing but space in
a memory where data is stored.
To create a file in a 'C' program following syntax is used,
FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.
Reading a File
There are three different functions dedicated to reading data from a file
fgetc(file_pointer): It returns the next character from the file pointed to by the file pointer. When the
end of the file has been reached, the EOF is sent back.
fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string in a buffer in
which the NULL character '\0' is appended as the last character.
fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and analyze data.
It reads characters from the file and assigns the input to a list of variable pointers variable_adresses
using conversion specifiers.
Writing to a File
In C, when you write to a file, newline characters '\n' must be explicitly added.
The stdio library offers the necessary functions to write to a file:
fputc(char, file_pointer): It writes a character to the file pointed to by file_pointer.
fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by file_pointer.
The string can optionally include format specifiers and a list of variables variable_lists.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
fprintf(fptr, "Hello All"); //Writing into the file
fclose(fptr);
return 0;
}
Output:
---------------------------------------------------------------------------------------------------------------------------
FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.
Reading a File
There are three different functions dedicated to reading data from a file
fgetc(file_pointer): It returns the next character from the file pointed to by the file pointer. When the
end of the file has been reached, the EOF is sent back.
fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string in a buffer in
which the NULL character '\0' is appended as the last character.
fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and analyze data.
It reads characters from the file and assigns the input to a list of variable pointers variable_adresses
using conversion specifiers.
Writing to a File
In C, when you write to a file, newline characters '\n' must be explicitly added.
The stdio library offers the necessary functions to write to a file:
fputc(char, file_pointer): It writes a character to the file pointed to by file_pointer.
fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by file_pointer.
The string can optionally include format specifiers and a list of variables variable_lists.
Close a file
One should always close a file whenever the operations on file are over.
It means the contents and links to the file are terminated. This prevents accidental damage to the file.
'C' provides the fclose( ) function to perform file closing operation. The syntax of fclose( ) is as
follows,
fclose (file_pointer);
Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
File Modes
File modes allow us to create, read, write, append or modify a file.
4. What is a file pointer? Explain the steps for sequential file operations.
File pointer is a pointer which is used to handle and keep track on the files being accessed.
A new data type called “FILE” is used to declare file pointer.
This data type is defined in stdio.h file.
File pointer is declared as FILE *fp. Where, ‘fp’ is a file pointer.
Sequential file operations
C supports the concept of file through which the data can be stored in the disk or secondary storage
device. So the data can be read when required. A file is a collection of data or text, placed on the
disk.
There are two types of files- sequential file and random access file.
In sequential file, data are kept sequential. As example if we want to access the 10th record, then
first 9 records should be read sequentially to reach the forty fourth record.
In sequential file type of files data is kept in sequential order if we want to read the last record of the
file, we need to read all records before that record so it takes more time.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen("c.dat", "wb+");
printf("Enter the integer data");
scanf("%d",&n);
while(n!=0)
{
putw(n,fp);
scanf("%d",&n);
}
rewind(fp);
printf("Reading data from file");
while((n=getw(fp))!=EOF)
{
printf("%d\n",n);
}
fclose(fp);
getch();
}
Output
Enter the integer data
10
20
34
45
0
Reading data from file
10
20
34
45
0
---------------------------------------------------------------------------------------------------------------------------
5. Compare fgets() and fputs() with an example.
fgets()
This function is used to read a string from a given file and copies the string to a memory location
which is referenced by an array.
Syntax: fgets(sptr,max,fptr);
Where,
sptr is a string pointer, which points to an array.
max is the length of the array.
fptr is a file pointer ,which points to a given file.
This function read max-1 characters and places them into array which is pointed by sptr.This function
read character until either a newline or an end of the file or size of the array occurs. It appends a null
character (‘\0’) at the end of the string. It returns a null pointer if either an end of file or an error
encountered.
fputs ()
This function is used to write a string to a given file.
Syntax: fputs (sptr, fptr);
Where,
sptr is a pointer which points to an array
fptr is a file pointer which is pointed to a given file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char str[300];
fp=fopen("hello.txt","w+");
fputs("hello c programming",fp);
rewind(fp);
printf("Reading data from file:\n%s",fgets(text,200,fp));
fclose(fp);
getch();
}
Output:
Reading data from file:
hello c programming
---------------------------------------------------------------------------------------------------------------------------
6. Write a program to copy the contents of one file to another file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output
Enter the filename to open for reading
source.txt
Enter the filename to open for writing
target.txt
Contents copied to target.txt
---------------------------------------------------------------------------------------------------------------------------
7. Write the syntax and example for fseek( ), ftell( ) and rewind( ) functions.
fseek( )
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file
at desired location.
Syntax:
int fseek(FILE *stream, long int offset, int whence)
Parameters:
stream − This is the pointer to a FILE object that identifies the stream.
offset − This is the number of bytes to offset from whence.
whence − This is the position from where offset is added. It is specified by one of the following
constants.
Return Value:
This function returns zero if successful, or else it returns a non-zero value.
ftell( )
The ftell() function returns the current file position of the specified stream.
We can use ftell() function to get the total size of a file after moving file pointer at the end of file.
Syntax:
long int ftell(FILE *stream)
Parameters:
stream − This is the pointer to a FILE object that identifies the stream.
rewind( )
The rewind() function sets the file pointer at the beginning of the stream.
It is useful to use stream many times.
Syntax:
void rewind(FILE *stream)
Parameters:
stream − This is the pointer to a FILE object that identifies the stream.
Return Value:
This function does not return any value.
Example Program:
#include<stdio.h>
int main()
{
/* Opening file in read mode */
FILE *fp = fopen("test.txt","w+");
Output
File pointer position before rewind: 13
File pointer position after rewind: 0
---------------------------------------------------------------------------------------------------------------------------