0% found this document useful (0 votes)
5 views5 pages

Unit4 Assignment Answers

Uploaded by

jenishsapkale58
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)
5 views5 pages

Unit4 Assignment Answers

Uploaded by

jenishsapkale58
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

BHAGWAN MAHAVIR UNIVERSITY

BHAGWAN MAHAVIR POLYTECHNIC


INFORMATION TECHNOLOGY ENGINEERING DEPARTMENT
UNIT-4 ASSIGNMENT – ANSWERS

Advance Computer Programming – Theory (2030107201)


Chapter 4: Files & Preprocessor Directives

Que 1: Answer the following Questions. (2 Marks)


1. Why use Preprocessor (Macro)?
The C Preprocessor is not part of the compiler but it extends the power of C programming language.
Macros (preprocessor directives) are used for the following reasons:
• Code Reusability: A macro defined once can be used multiple times throughout the program.
• Header File Inclusion: Allows inclusion of standard or user-defined header files using #include.
• Macro Expansion: Replaces an identifier with a value or expression before compilation using
#define.
• Conditional Compilation: Allows blocks of code to be compiled or skipped based on conditions.
• Line Control: Controls line numbering for error reporting.
• Processed Before Compilation: Preprocessor directives begin with # and are processed before
the actual compilation begins.

2. List down Preprocessor Directives.


There are four types of preprocessor directives in C:
Type Directives

File Inclusion #include

Macro Substitution #define

Conditional #if, #elif, #else, #endif, #ifdef, #ifndef, #undef

Miscellaneous #pragma, #error, #line

3. Explain fopen() and fclose().


fopen():
The fopen() function is used to open a file. It returns a pointer to the FILE structure. If the file cannot be
opened, it returns NULL.
Syntax: FILE *fopen(const char *filename, const char *mode);
Common file modes:
• "r" – Open file for reading.
• "w" – Open file for writing (creates new or truncates existing).
• "a" – Open file for appending.
• "r+" – Open for reading and writing.
Example:
FILE *fp; fp = fopen("[Link]", "r"); if(fp == NULL) printf("File not found!");

fclose():
The fclose() function closes a file that was opened with fopen(). It flushes all buffers associated with the file
and releases the FILE pointer. It returns 0 on success and EOF on failure.
Syntax: int fclose(FILE *fp);
Example: fclose(fp);

4. Explain putc() and getc().


putc():
putc() writes a single character to a file. It takes the character and the file pointer as arguments.
Syntax: int putc(int ch, FILE *fp);
Example: FILE *fp = fopen("[Link]","w"); putc('A', fp);

getc():
getc() reads a single character from a file. It returns the character read as an integer, or EOF if the end of
file is reached.
Syntax: int getc(FILE *fp);
Example: FILE *fp = fopen("[Link]","r"); char ch = getc(fp); printf("%c", ch);

5. What is Predefined Macros?


C programming language defines a number of built-in macros that are always available. These are called
predefined macros. They provide useful information about the source file and compilation.
Macro Description

NULL Value of a null pointer constant.

EXIT_SUCCESS Value returned by exit() on successful completion.

EXIT_FAILURE Value returned by exit() on failure.

RAND_MAX Maximum value returned by the rand() function.

__FILE__ Current filename as a string.

__LINE__ Current line number as an integer constant.

__DATE__ Current date in 'MMM DD YYYY' format.

__TIME__ Current time in 'HH:MM:SS' format.

6. Define Command Line Argument.


Command line arguments are the arguments/parameters passed to the program at the time of execution
from the command line/terminal. In C, they are handled by the main() function using two parameters:
• argc (argument count): Number of arguments passed including the program name.
• argv (argument vector): Array of strings representing the actual arguments.
Syntax: int main(int argc, char *argv[])
#include <stdio.h> int main(int argc, char *argv[]) { printf("Program: %s\n",
argv[0]); printf("Total args: %d\n", argc); return 0; }

Que 2: Answer the following Questions. (3 Marks)


1. Explain Features of Preprocessor.
The C Preprocessor extends the power of C programming language. Its functionality comes before
compilation of source code and instructs the compiler to do required preprocessing. The key features are:
1. Header File Inclusion (#include):
The preprocessor allows inclusion of standard or user-defined header files. It replaces the #include
directive with the entire content of the specified header file before compilation. Example: #include
<stdio.h> inserts the standard I/O library.

2. Macro Substitution (#define):


The preprocessor replaces all occurrences of a defined macro identifier with its value or expression
throughout the code. It supports both simple macros (#define PI 3.14) and macros with arguments
(#define area(r) (3.14*r*r)).

3. Conditional Compilation (#if, #ifdef, #ifndef, etc.):


This feature allows selective compilation of code blocks based on conditions. Only the code satisfying
the condition is compiled, rest is ignored. Useful for cross-platform code and debugging.

4. Miscellaneous Directives (#pragma, #error, #line):


#pragma issues compiler-specific commands. #error stops compilation and prints an error message.
#line resets the line number counter for error reporting.

5. Processed Before Compilation:


All preprocessor directives begin with the # symbol, do not end with a semicolon, and are processed
entirely before the actual compilation of source code begins.

6. No Type Checking for Macros:


Unlike functions, macro arguments do not require data type declarations. Any numeric type (int, float,
etc.) can be passed as a macro argument.

Que 3: Answer the following Questions. (5 Marks)


1. Explain Concept of File Management. Opening, Reading and Closing the Files with
Examples.
File Management in C: File management refers to the process of storing data permanently on secondary
storage (disk) through a C program. Unlike variables that store data temporarily in memory (lost when
program ends), files allow persistent storage. C provides built-in functions for creating, opening, reading,
writing, and closing files.
(a) Opening a File – fopen():
A file must be opened before any read/write operation. The fopen() function opens a file and returns a
FILE pointer.
Syntax: FILE *fp = fopen("filename", "mode");

Mode Description

"r" Open for reading. File must exist.

"w" Open for writing. Creates new file or truncates existing.

"a" Open for appending. Data written at end of file.

"r+" Open for both reading and writing.

"w+" Open for reading and writing. Truncates file.

"a+" Open for reading and appending.

(b) Reading a File – getc() / fscanf() / fgets():


Once a file is opened in read mode, its contents can be read using various functions:
• getc(fp) – reads one character at a time. • fscanf(fp, format, &var;) – reads formatted
data. • fgets(str, n, fp) – reads a line of text.
Example – Opening, Reading and Closing a file:
#include <stdio.h> int main() { FILE *fp; char ch; // Opening the file fp =
fopen("[Link]", "r"); if(fp == NULL) { printf("Error: File not found!\n");
return 1; } // Reading the file character by character while((ch = getc(fp)) != EOF)
{ printf("%c", ch); } // Closing the file fclose(fp); return 0; }

(c) Closing a File – fclose():


After all operations are done, the file must be closed using fclose(). This flushes all pending data to the file
and releases the file pointer. Syntax: fclose(fp);

2. Explain Preprocessors in Detail: #define, #include, #line Directive.


I. #define (Macro Substitution Directive):
The #define directive is a simple substitution macro. It substitutes all occurrences of the defined identifier
and replaces them with an expression. There are two types:
a) Simple Macro:
Syntax: #define identifier value
• identifier – name used in program (usually in CAPITALS to distinguish from variables). • value –
value to be substituted for the identifier.
// Simple macro example #include <stdio.h> #define PI 3.14 int main() { int radius =
10; float area = PI * radius * radius; printf("Area of Circle = %f", area); } //
Output: Area of Circle = 314.000000

b) Macro with Arguments:


Macro definitions can include parameters. Data type declaration is not needed for macro arguments. Any
numeric values (int, float etc.) can be passed.
// Macro with arguments example #include <stdio.h> #define area(r) (3.14*r*r) int
main() { int radius = 10; float a = area(radius); printf("Area of Circle = %f", a);
} // Output: Area of Circle = 314.000000

II. #include (File Inclusion Directive):


The #include directive is used to include a header file inside a C program. The preprocessor replaces
the #include statement with the entire content of the specified header file before compilation.
Two forms of #include:
• #include <stdio.h> – Used for standard/system header files. The preprocessor searches in
the standard system directories.
• #include "big.h" – Used for user-defined header files. The preprocessor first checks the
current directory, then system directories.
// File inclusion example #include <stdio.h> // Standard header #include "myfile.h"
// User defined header int main() { printf("Hello World!"); return 0; }

III. #line Directive (Miscellaneous Directive):


The #line directive tells the compiler that the next line of source code is at the line number specified by
the constant in the #line directive. It resets the line counter used by the __LINE__ predefined macro.
Syntax: #line <line_number> [File Name]
• line_number – The new line number to assign to the next line.
• File Name – Optional. Specifies a new file name for error messages.
// #line directive example int main() { #line 700 printf("Line Number %d\n",
__LINE__); // prints 700 printf("Line Number %d\n", __LINE__); // prints 701
printf("Line Number %d\n", __LINE__); // prints 702 return 0; } // Output: // 700 //
701 // 702
Use case: The #line directive is primarily useful for tools that generate C source code. It helps in mapping
error messages back to the original source rather than the generated code.

— End of Assignment Answers —

You might also like