BIT102 ยท 2080 ยท 5 marks
Write short notes on: a) Macro Write short notes on: b) Opening and closing file [2.5+2.5]
Write short notes on: a) Macro Write short notes on: b) Opening and closing file [2.5+2.5]
Quick answer
A macro is a preprocessor directive in C that allows a name (identifier) to be associated with a piece of code, a constant, or an expression. The C preprocessor replaces every occurrence of the macro name with its defined text before actual compilation begins.
Short Notes
a) Macro
Types of Macros
1. Object-like Macro (Simple/Symbolic Constant)
#define PI 3.14159
#define MAX 100
Every occurrence of PI in the code is replaced by 3.14159.
2. Function-like Macro (Macro with Arguments)
#define SQUARE(x) ((x)*(x))
#define MAX(a,b) ((a)>(b) ? (a) : (b))
Usage: SQUARE(5) is replaced by ((5)*(5)) = 25.
Key Points
- Defined using
#definedirective. - Processed by the preprocessor, not the compiler.
- No type checking is performed (unlike functions).
- Parentheses should be used carefully to avoid operator precedence errors.
- Macros can be undefined using
#undef. - They make code more readable, portable, and easy to maintain.
b) Opening and Closing a File
In C, file handling is done using the standard library <stdio.h>. Before reading from or writing to a file, it must be opened, and after operations are complete, it must be closed.
Opening a File
The fopen() function is used to open a file.
Syntax:
FILE *fptr;
fptr = fopen("filename", "mode");
FILE *is a pointer to a file structure.- If the file cannot be opened,
fopen()returnsNULL.
File Opening Modes
| Mode | Description |
|---|---|
"r" | Open for reading (file must exist) |
"w" | Open for writing (creates new or truncates existing) |
"a" | Open for appending (creates if not exists) |
"r+" | Open for both reading and writing |
"w+" | Open for reading and writing (truncates) |
"a+" | Open for reading and appending |
Closing a File
The fclose() function is used to close an opened file.
Syntax:
fclose(fptr);
- It flushes any unwritten data to the file.
- Releases the file pointer resource.
- Returns
0on success,EOFon failure.
Example
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("data.txt", "w"); // Open file for writing
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fptr, "Hello, File!\n"); // Write to file
fclose(fptr); // Close the file
return 0;
}
Note: Always check if
fopen()returnsNULLbefore performing file operations, and always close the file after use to prevent data loss or resource leaks.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.