Thursday, January 15, 2026

c lan.UNIT 5 MIMP Q&A

1. Explain File Handling in C. Explain file operations: open, read, write and close.


Introduction : File Handling in C

File handling in C is used to store data permanently in a file on disk.
Normally, data stored in variables is lost when the program ends.
To save data for future use, we use files.

A file is a collection of data stored in secondary memory (hard disk).

C provides file handling functions through the header file:

#include <stdio.h>

File handling allows us to:

  • Create a file

  • Open a file

  • Read data from a file

  • Write data into a file

  • Close a file


File Pointer

In C, a file is accessed using a pointer of type FILE.

FILE *fp;

File Operations

The main file operations are:

  1. Open a file

  2. Read from a file

  3. Write into a file

  4. Close a file


1. Opening a File

To open a file, the function fopen() is used.

Syntax:

fp = fopen("filename", "mode");

Modes:

ModeMeaning
rRead
wWrite
aAppend
r+Read and write
w+Read and write (overwrite)
a+Read and append

Example:

fp = fopen("data.txt", "w");

This opens data.txt in write mode.


2. Writing into a File

To write data into a file, we use:

  • fprintf()

  • fputs()

  • fputc()

Syntax:

fprintf(fp, "format", variables);

Example:

fprintf(fp, "Hello World");

3. Reading from a File

To read data from a file, we use:

  • fscanf()

  • fgets()

  • fgetc()

Syntax:

fscanf(fp, "format", &variables);

Example:

fscanf(fp, "%s", str);

4. Closing a File

After completing file operations, the file must be closed using fclose().

Syntax:

fclose(fp);

Closing a file:

  • Saves the data properly

  • Frees memory

  • Avoids file corruption


Example Program

#include <stdio.h>
#include <conio.h>

void main()
{
    FILE *fp;
    char name[20];

    fp = fopen("student.txt", "w");
    printf("Enter name: ");
    scanf("%s", name);
    fprintf(fp, "%s", name);
    fclose(fp);

    fp = fopen("student.txt", "r");
    fscanf(fp, "%s", name);
    printf("Name from file: %s", name);
    fclose(fp);
}

Output on screen:

Enter name: Parmar Name from file: Parmar

Advantages of File Handling

  • Stores data permanently

  • Useful for large data storage

  • Helps in backup and recovery

  • Data can be shared between programs

2. Explain file modes (r, w, a, r+, w+, a+) with examples


Introduction

When opening a file in C using fopen(), we must specify the file mode.
The file mode tells the compiler how the file will be used (read, write, append, etc.).

Syntax:

fp = fopen("filename", "mode");

Example:

fp = fopen("data.txt", "r");

File Modes in C

ModeMeaningIf file existsIf file does not exist
rRead onlyOpens fileError
wWrite onlyDeletes old dataCreates new file
aAppendAdds at endCreates new file
r+Read & writeOpens fileError
w+Read & writeDeletes old dataCreates new file
a+Read & appendAdds at endCreates new file

Explanation with Examples


1. Mode: r (Read mode)

    • Opens an existing file for reading.

    • File must exist.

    • Data cannot be modified.

fp = fopen("data.txt", "r");

2. Mode: w (Write mode)

  • Opens a file for writing.

  • Creates a new file if it does not exist.

  • Deletes old data if file already exists.

fp = fopen("data.txt", "w");

fprintf(fp, "Hello");

3. Mode: a (Append mode)

    • Opens a file for appending data.

    • New data is added at the end of file.

    • Old data is not deleted.

fp = fopen("data.txt", "a");
fprintf(fp, "Welcome");

4. Mode: r+ (Read and Write)

    • Opens an existing file for both reading and writing.

    • File must exist.

fp = fopen("data.txt", "r+");
fscanf(fp, "%s", str);
fprintf(fp, "NewData");

5. Mode: w+ (Read and Write)

  • Used to read and write.

  • Old data is erased.

  • New file is created if not exists.

fp = fopen("data.txt", "w+");
fprintf(fp, "Start");

6. Mode: a+ (Read and Append)

  • Used to read and add data at end.

  • Old data is not deleted.

fp = fopen("data.txt", "a+");
fprintf(fp, "End");

Conclusion

File modes define how a file is opened and used.
Choosing the correct mode is important to avoid data loss or file errors.

3. Differentiate Text Files and Binary Files with Examples


Introduction

In C, files are mainly classified into Text files and Binary files.
The difference is based on how data is stored and read from the file.


Text File

A text file stores data in human-readable form (ASCII characters).

  • Data is stored as characters.

  • We can open and read it using Notepad.

  • Suitable for small and readable data.

Example:

fp = fopen("data.txt", "w");
fprintf(fp, "100");

File content:

100

Binary File

A binary file stores data in machine-readable (binary) form.

  • Data is stored in binary format.

  • Cannot be read directly in Notepad.

  • Suitable for large and complex data.

Example:

fp = fopen("data.dat", "wb");
fwrite(&num, sizeof(num), 1, fp);

Difference Between Text and Binary Files

BasisText FileBinary File
StorageCharacter formatBinary format
ReadableHuman readableNot human readable
SizeLargerSmaller
SpeedSlowerFaster
Extension.txt.dat, .bin
Functionsfprintf, fscanffwrite, fread
UseSimple dataStructured data

Example Programs

Text File Example

#include <stdio.h>
#include <conio.h>

void main()
{
    FILE *fp;
    int n = 10;

    fp = fopen("num.txt", "w");
    fprintf(fp, "%d", n);
    fclose(fp);
}

Binary File Example

#include <stdio.h>
#include <conio.h>

void main()
{
    FILE *fp;
    int n = 10;

    fp = fopen("num.dat", "wb");
    fwrite(&n, sizeof(n), 1, fp);
    fclose(fp);
}

Conclusion

Text files store data in readable form and are easy to use.
Binary files store data in binary form and are efficient and fast.
The choice depends on the type and size of data.

4. Explain File I/O Functions: fopen(), fclose(), fprintf(), fscanf(), fgetc(), fgets()


Introduction

File Input/Output (I/O) functions are used to read data from a file and write data into a file.
These functions are defined in the header file:

#include <stdio.h>

1. fopen()

Used to open a file.

Syntax:

fp = fopen("filename", "mode");

Example:

fp = fopen("data.txt", "r");

2. fclose()

Used to close a file.

Syntax:

fclose(fp);

Example:

fclose(fp);

3. fprintf()

Used to write formatted output into a file.

Syntax:

fprintf(fp, "format", variables);

Example:

fprintf(fp, "Name: %s", name);

4. fscanf()

Used to read formatted input from a file.

Syntax:

fscanf(fp, "format", &variables);

Example:

fscanf(fp, "%d", &n);

5. fgetc()

Used to read a single character from a file.

Syntax:

ch = fgetc(fp);

Example:

char ch = fgetc(fp);

6. fgets()

Used to read a line (string) from a file.

Syntax:

fgets(string, size, fp);

Example:

fgets(str, 50, fp);

Summary Table

FunctionUse
fopen()Open file
fclose()Close file
fprintf()Write formatted data
fscanf()Read formatted data
fgetc()Read one character
fgets()Read a string/line

Example Program

#include <stdio.h>
#include <conio.h>

void main()
{
    FILE *fp;
    char name[20];
    char ch;

    fp = fopen("test.txt", "w");
    fprintf(fp, "Hello\nWorld");
    fclose(fp);

    fp = fopen("test.txt", "r");
    ch = fgetc(fp);
    printf("First char: %c\n", ch);
    fgets(name, 20, fp);
    printf("Line: %s", name);
    fclose(fp);
}
OUTPUT
First char: H
Line: ello


Conclusion

These file I/O functions help us open files, read data, write data and close files easily.
They are essential for permanent data storage.

6. Explain Random Access Functions: fseek(), ftell(), rewind() with Examples


Introduction

Normally, file reading and writing is done sequentially.
Random access functions allow us to move the file pointer to any position in the file and access data directly.

Random access is useful when we want to:

  • Modify a particular record

  • Read a specific part of a file

  • Skip some data


File Pointer Position

Each file has a file position indicator that shows the current position in the file.

Start → 0 → 1 → 2 → 3 → ... → End
          ^
        Pointer

1. fseek()

Used to move the file pointer to a specific position.

Syntax:

fseek(fp, offset, origin);
ParameterMeaning
fpFile pointer
offsetNumber of bytes to move
originStarting position

Origin values:

ConstantMeaning
SEEK_SETBeginning of file
SEEK_CURCurrent position
SEEK_ENDEnd of file

Example:

fseek(fp, 5, SEEK_SET);   // Move to 5th byte from start

2. ftell()

Used to get the current position of file pointer.

Syntax:

pos = ftell(fp);

Example:

long pos;
pos = ftell(fp);
printf("Position: %ld", pos);

3. rewind()

Moves the file pointer back to the beginning of the file.

Syntax:

rewind(fp);

Example:

rewind(fp);

Example Program

#include <stdio.h>
#include <conio.h>

void main()
{
    FILE *fp;
    char ch;
    long pos;

    fp = fopen("data.txt", "w+");
    fputs("ABCDEFGH", fp);

    fseek(fp, 3, SEEK_SET);   // Move to 4th character
    ch = fgetc(fp);
    printf("Character at position 3: %c\n", ch);

    pos = ftell(fp);
    printf("Current position: %ld\n", pos);

    rewind(fp);              // Move to start
    ch = fgetc(fp);
    printf("First character: %c\n", ch);

    fclose(fp);
}

Final Output (Exam Ready)

Character at position 3: D Current position: 4 First character: A

Summary Table

FunctionUse
fseek()Move pointer to given position
ftell()Find current position
rewind()Move pointer to start

7. Explain Bitwise Operators with Truth Tables and Examples


Introduction

Bitwise operators perform operations on individual bits of integer data.
They are used for low-level programming, optimization, masking, and hardware related operations.

All bitwise operators work on binary form of numbers.


List of Bitwise Operators

OperatorNameMeaning
&Bitwise AND    AND on each bit
|Bitwise OR    OR on each bit
^Bitwise XOR     Exclusive OR
~Bitwise NOT   1's complement
<<Left shift   Shift bits left
>>Right shift    Shift bits right

1. Bitwise AND (&)

Truth Table

A  B    A & B
000
010
100
111

Example

int a = 5;   // 0101
int b = 3;   // 0011
int c = a & b;  // 0001 = 1

2. Bitwise OR (|)

Truth Table

| A | B |    A | B   |
|---|---|------------|
| 0 | 0 |       0       |
| 0 | 1 |       1       |  
| 1 | 0 |       1       |
| 1 | 1 |       1       |

Example

int a = 5;  // 0101
int b = 3;  // 0011
int c = a | b;  // 0111 = 7

3. Bitwise XOR (^)

Truth Table

A   B    A ^ B
000
011
101
110

Example

int a = 5;  // 0101
int b = 3;  // 0011
int c = a ^ b;  // 0110 = 6

4. Bitwise NOT (~)

Truth Table

A~A
01
10

Example

int a = 5;   // 00000101
int b = ~a;  // 11111010 = -6 (in 2's complement)

5. Left Shift (<<)

Shifts bits to left and fills 0 on right.

int a = 5;   // 0101
int b = a << 1;  // 1010 = 10

6. Right Shift (>>)

Shifts bits to right.

5 >> 1 → 0101 >> 1 = 0010 → Result = 2

Example Program

#include <stdio.h>
#include <conio.h>

void main()
{
    int a = 5, b = 3;
    printf("a & b = %d\n", a & b);
    printf("a | b = %d\n", a | b);
    printf("a ^ b = %d\n", a ^ b);
    printf("~a = %d\n", ~a);
    printf("a << 1 = %d\n", a << 1);
    printf("a >> 1 = %d\n", a >> 1);
}

Output of Bitwise Operators :

a = 5, b = 3 a & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 a >> 1 = 2



8. Explain Preprocessor Directives: #include, #define, and Macro Expansion


Introduction

Preprocessor directives are instructions given to the C compiler before actual compilation starts.
They begin with # symbol and are processed by the preprocessor.

They are used to:

  • Include header files

  • Define constants and macros

  • Perform macro expansion


1. #include Directive

Used to include header files into a program.

Syntax:

#include <stdio.h>
#include "myfile.h"

Types:

  1. System header file

#include <stdio.h>
  1. User-defined header file

#include "myfile.h"

2. #define Directive

Used to define constants or macros.

Syntax:

#define PI 3.14
#define SQR(x) (x*x)

3. Macro Expansion

Macro expansion means replacing the macro name with its definition before compilation.

Example:

#define PI 3.14
#define SQR(x) (x*x)

float a = PI;
int b = SQR(5);

After macro expansion:

float a = 3.14;
int b = (5*5);

Example Program

#include <stdio.h>
#define PI 3.14
#define SQR(x) (x*x)

void main()
{
    float r = 5;
    printf("Area = %f", PI * SQR(r));
}

Output

Area = 78.500000

Advantages of Preprocessor Directives

  • Improves code readability

  • Makes program easier to modify

  • Saves time and reduces errors

  • Helps in code reuse

Below is your GTU-style long answer in easy English 👇
(with definition, syntax, explanation and example program)


9. Explain Command-Line Arguments with

Example Program


Introduction

Command-line arguments are values passed to a program at the time of execution from

the command prompt.

They allow the user to give input without using scanf().


Syntax of main() with Command-Line Arguments

int main(int argc, char *argv[])
ParameterMeaning
argcArgument count
argvArgument vector (array of strings)

Explanation

  • argc stores the number of arguments.

  • argv[] stores the actual arguments as strings.

  • argv[0] is the program name.


Example Program

#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])
{
    int a, b, sum;

    a = atoi(argv[1]);
    b = atoi(argv[2]);
    sum = a + b;

    printf("Sum = %d", sum);
    return 0;
}

How to Run the Program

add 10 20

Output:

Sum = 30

Memory View

argc = 3
argv[0] = "add"
argv[1] = "10"
argv[2] = "20"

atoi() means

👉 atoi = ASCII to Integer

It is a library function used to convert a string (text number) into an integer value.

10. Write a program to copy content from one file to another and explain it line-by-line


Program: Copy Content from One File to Another

#include <stdio.h>
#include <conio.h>

void main()
{
    FILE *fp1, *fp2;
    char ch;

    fp1 = fopen("source.txt", "r");      // open source file in read mode
    fp2 = fopen("dest.txt", "w");        // open destination file in write mode

    while ((ch = fgetc(fp1)) != EOF)     // read one character until end of file
    {
        fputc(ch, fp2);                  // write character into destination file
    }

    fclose(fp1);                         // close source file
    fclose(fp2);                         // close destination file

    printf("File copied successfully.");
}

Line-by-Line Explanation

#include <stdio.h>

Includes standard input-output functions like fopen, fgetc, fputc.


#include <conio.h>

Used for console input/output (optional, Turbo C style).


void main()

Program execution starts here.


FILE *fp1, *fp2;

Declares two file pointers:

  • fp1 for source file

  • fp2 for destination file


char ch;

Variable to store one character at a time.


fp1 = fopen("source.txt", "r");

Opens source.txt in read mode.


fp2 = fopen("dest.txt", "w");

Opens dest.txt in write mode.


while ((ch = fgetc(fp1)) != EOF)

Reads one character from source file until End Of File.


fputc(ch, fp2);

Writes that character into destination file.


fclose(fp1);

Closes source file.


fclose(fp2);

Closes destination file.


printf("File copied successfully.");

Displays message on screen.


Output

File copied successfully.

No comments:

Post a Comment

Personality Development[imp]

Short Questions Answers: Q.1 Define Personality. Personality is the combination of a person’s thoughts, feelings, and behavior that makes th...