0% found this document useful (0 votes)
7 views11 pages

Pps Unit3 Qa

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

Pps Unit3 Qa

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1. Briefly explain the pre-processor directives in detail.

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

 A macro name is generally written in capital letters.


 If suitable and relevant names are given macros increase the readability.
 If a macro is used in any program and we need to make some changes throughout the program we
can just change the macro and the changes will be reflected everywhere in the program.

Example : Simple macro


#define LOWER 30
void main()
{
int i;
for (i=1;i<=LOWER; i++)
{
printf("\n%d", i);
}
}

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.

There are two ways of the file inclusion statement:


i) #include “file-name”
ii) #include <file-name>

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

 There are two directives:


i) #undef : This directive is used in relation to the #define directive. It is used to undefine a
defined macro.
ii) #pragma : It is a specialized and rarely used directive. They are used for turning on and off
certain features.
---------------------------------------------------------------------------------------------------------------------------
2. Explain Creating Reading and writing text and binary files.

There are two types of files,


 Text files
 Binary files
1. Text files
 Text files are the normal .txt files. You can easily create text files using any simple text editors such
as Notepad.
 When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.
 They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.
2. Binary files
 Binary files are mostly the .bin files in your computer.
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 They can hold a higher amount of data, are not readable easily, and provides better security than text
files.

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.

 fopen is a standard function which is used to open a file.


 If the file is not present on the system, then it is created and then opened.
 If a file is already present on the system, then it is directly opened using this function.
 fp is a file pointer which points to the type file.
 File modes allow us to create, read, write, append or modify a file.

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

// creating file pointer to work with files


FILE *fptr;

// opening / Creating file in writing mode


fptr = fopen("program.txt", "w");

// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
fprintf(fptr, "Hello All"); //Writing into the file
fclose(fptr);
return 0;
}

Output:

---------------------------------------------------------------------------------------------------------------------------

3. Explain Steps for file operations and different modes of files.


File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
 Creation of the new file
 Opening an existing file
 Reading from the file
 Writing to the file
 Closing the file

Create a File / Opening an existing file


 To create a file or open an existing 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.

 fopen is a standard function which is used to open a file.


 If the file is not present on the system, then it is created and then opened.
 If a file is already present on the system, then it is directly opened using this function.
 fp is a file pointer which points to the type file.
 File modes allow us to create, read, write, append or modify a file.

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);

 The fclose function takes a file pointer as an argument.


 The file associated with the file pointer is then closed with the help of fclose function. It returns 0 if
close was successful and EOF (end of file) if there is an error has occurred while file closing.

File Modes
 File modes allow us to create, read, write, append or modify a file.

There are many modes for opening a file:


 r - open a file in read mode
 w - opens or create a text file in write mode
 a - opens a file in append mode
 r+ - opens a file in both read and write mode
 a+ - opens a file in both read and write mode
 w+ - opens a file in both read and write mode
 rb - opens a binary file in read mode
 wb - opens a binary file in write mode
 ab - opens a binary file in append mode
 rb+ - opens a binary file in read and write mode
 wb+ - opens a binary file in read and write mode
 ab+ - opens a binary file in read and write mode
---------------------------------------------------------------------------------------------------------------------------

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.

 The steps for file operation in C programming are as follows:


 Open a file.
 To open a file you need to use the fopen function, which returns a FILE pointer. Once
we have opened a file, we can use the FILE pointer to let the compiler perform input
and output functions on the file.
 Read the file or write data in the file.
 The file read operations can be performed using functions fscanf or fgets.
 Close the file.
 After every successful fie operations, you must always close a file. For closing a file,
we have to use fclose function.

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.

Example program for fgets() and fputs()


 Write a program to write string into a file using fputs() and read the same strings from file using
fgets() and display on the output screen.

#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;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);

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.

There are 3 constants used in the fseek() function for whence:


 SEEK_SET: Beginning of file
 SEEK_CUR: Current position of the file pointer
 SEEK_END: End of file

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+");

fputs("This is C program", fp);


fseek( fp, -4, SEEK_CUR); //Set current position

/* Printing position of file pointer */


printf("File pointer position before rewind: %ld\n", ftell(fp));

rewind(fp); // sets the file pointer at the beginning

/* Printing position of file pointer */


printf("File pointer position after rewind: %ld\n", ftell(fp));
return 0;
}

Output
File pointer position before rewind: 13
File pointer position after rewind: 0

---------------------------------------------------------------------------------------------------------------------------

You might also like