Thursday, October 9, 2025

BCA 1 : Unit -5: Pointers and File Handling in C for IMCA/BCA Students



I.M.C.A / BCA  Semester – 1

C Language

Unit – 5


Unit -5: Pointers and File Handling in C

Contents

1. Introduction to Pointer 3

2. Pointer to Variable. 3

3. Pointer to Array. 4

4. Array of Pointer 4

5. Pointer to Structure. 5

6. Pointers within Structure. 5

7. Passing Pointer to UDF. 6

8. Pointer to Pointer 6

9. Use of Pointers in Dynamic Programming. 7

10. Command Line Arguments. 7

11. Concept of Data Files. 8

12. File Handling Functions. 8

13. I/O Operations. 11

 


 

  • A pointer is a variable that stores the memory address of another variable.
  • Declared using * symbol. Example: int *ptr;.
  • If int a = 10;, then ptr = &a; stores the address of a.
  • The operator & is used to get the address of a variable.
  • The operator * (dereference) is used to access the value stored at that address.
  • Pointers provide direct memory access, making C a powerful language.
  • They reduce redundancy by avoiding multiple copies of data.
  • Useful in arrays, strings, functions, structures, and dynamic memory.
  • Pointers are widely used in system programming and data structures.
  • Example:
  • int a=10; int *p=&a; printf("%d", *p); // prints 10
  • A pointer can point to a simple variable.
  • Example:
  • int x=5; int *p; p=&x;
  • p stores the address of x.
  • *p gives the value of x (i.e., 5).
  • We can change the variable value via pointer: *p=20; // x=20.
  • This helps in efficient memory management.
  • It reduces the need for returning multiple values in functions.
  • Pointers act as an alias to the variable.
  • Used in function parameters, reference passing, and memory access.
  • Example:
  • printf("Address=%p, Value=%d", p, *p);

 

  • A pointer can point to the first element of an array.
  • Example:
  • int arr[5]={10,20,30,40,50};
  • int *p=arr;
  • Here, p points to arr[0].
  • *(p+1) gives arr[1].
  • Pointers provide an alternate way of accessing array elements.
  • arr[i] is equivalent to *(arr+i).
  • This helps in fast iteration through arrays.
  • Used in passing arrays to functions efficiently.
  • Useful in searching, sorting, and matrix operations.
  • Accessing via pointer avoids copying the entire array.
  • An array can also store multiple pointers.
  • Example:
  • char *names[] = {"Raj", "Amit", "Neha"};
  • Each element points to a string.
  • Useful in handling multiple strings.
  • Instead of 2D character arrays, array of pointers is memory efficient.
  • Can be used in dynamic string handling.
  • Example: Storing file names or student names.
  • Helps in function pointers, memory tables, and lookup operations.
  • Used in programs like command line arguments.
  • It saves memory as only addresses are stored.

 

  • Pointers can store addresses of structures.
  • Example:
  • struct Student {int id; char name[20];};
  • struct Student s1={101,"Raj"}, *p=&s1;
  • Access members with p->id instead of (*p).id.
  • -> is called the arrow operator.
  • Useful in linked lists and dynamic structures.
  • Makes memory allocation and referencing easier.
  • Saves memory in passing large structures to functions.
  • Commonly used in file handling and databases.
  • Provides efficient record management.
  • Structures can contain pointer members.
  • Example:
  • struct Student {int *marks; char *name;};
  • Useful when memory is allocated dynamically for strings/arrays.
  • Helps in dynamic allocation of records.
  • Used in linked lists, trees, and graphs.
  • Makes structures flexible in size.
  • Allows better handling of variable length data.
  • Useful in real-time applications and data models.
  • Helps reduce unnecessary memory usage.
  • Example: Database storing variable-length names.

 

  • Pointers can be passed to functions as arguments.
  • Provides call by reference capability.
  • Example:
  • void update(int *p){ *p=50; }
  • int main(){ int x=10; update(&x); }
  • The original variable changes when modified inside function.
  • This is efficient as no copying of data occurs.
  • Useful in swapping, sorting, and mathematical operations.
  • Allows functions to modify arrays and structures directly.
  • Reduces program complexity.
  • Used in memory manipulation and system programming.
  • A pointer can also store the address of another pointer.
  • Declared as int **pp;.
  • Example:
  • int x=5; int *p=&x; int **pp=&p;
  • **pp gives value of x.
  • Helps in handling 2D arrays and memory tables.
  • Useful in function returning a pointer.
  • Provides multi-level indirection.
  • Widely used in dynamic memory allocation (malloc with arrays).
  • Common in complex data structures like linked lists, trees.

 

  • Dynamic memory means allocating memory at runtime.
  • Functions: malloc(), calloc(), realloc(), free().
  • Example:
  • int *p = (int*)malloc(5*sizeof(int));
  • Pointers manage heap memory efficiently.
  • Used in building dynamic data structures like linked lists.
  • Useful for applications where size is not known in advance.
  • Prevents wastage of memory.
  • Makes program flexible and memory efficient.
  • Example: Storing records of students when number is unknown.
  • Command line arguments allow passing values to main() function.
  • Syntax: int main(int argc, char *argv[]).
  • argc → number of arguments, argv[] → argument list.
  • Example:
  • ./a.out file.txt
  • Here argv[1] = "file.txt".
  • Useful in file operations and automation scripts.
  • Helps in passing file names, options, inputs.
  • Used in Linux commands, utility programs.
  • Makes program flexible without recompilation.

 

  • Files are used to store data permanently.
  • Unlike variables, file data is not lost after program ends.
  • C provides file handling functions for reading/writing data.
  • Files can be of two types: text files and binary files.
  • File handling is done using FILE pointer (FILE *fp).
  • Example:
  • FILE *fp = fopen("data.txt","w");
  • File modes: "r" (read), "w" (write), "a" (append).
  • Helps in data storage, retrieval, and transfer.
  • Used in building databases, word processors, compilers.
  • File handling is the basis of real-world applications.

 

1. fopen() → Opens a file

  • fopen() is used to open a file and associate it with a file pointer.
  • Syntax: FILE *fp = fopen("filename.txt", "mode");.
  • Modes include: "r" (read), "w" (write), "a" (append), "r+" (read/write).
  • Returns NULL if the file cannot be opened.
  • Example:
  • FILE *fp = fopen("data.txt", "w");

 

2. fclose() → Closes a file

  • fclose() is used to close a file opened with fopen().
  • It releases memory and ensures data is written to disk.
  • Syntax: fclose(fp);.
  • Returns 0 on success, EOF on error.
  • Always close files to prevent data loss.

 


 

3. fprintf(), fscanf() → Write/read formatted text

  • fprintf() writes formatted output to a file (like printf() but for files).
  • fscanf() reads formatted input from a file (like scanf()).
  • Example:
  • fprintf(fp, "ID=%d", 101);
  • fscanf(fp, "%d", &id);

 

4. getw(), putw() → Read/write integers

  • putw() writes an integer to a file.
  • getw() reads an integer from a file.
  • They are simpler alternatives to fprintf/fscanf for integers.
  • Example:
  • putw(100, fp);
  • int x = getw(fp);

 

5. fseek(), ftell(), rewind() → Move file pointer

  • fseek() moves the file pointer to a specific position.
  • ftell() returns the current position of the pointer.
  • rewind() sets the file pointer to the beginning.
  • Example:
  • fseek(fp, 0, SEEK_END);
  • long pos = ftell(fp);
  • rewind(fp);

 

6. freopen() → Reopen file with new mode

  • freopen() opens an already open file with a new mode.
  • Useful for redirecting standard input/output to files.
  • Syntax: freopen("file.txt", "w", stdout);.
  • Example: redirecting output of printf to a file.

 


 

7. remove(), rename() → Delete/rename file

  • remove("file.txt"); deletes a file from disk.
  • rename("old.txt","new.txt"); renames a file.
  • Both return 0 on success, -1 on failure.
  • Commonly used in file management programs.

 

8. feof(), ferror() → End-of-file, error checking

  • feof(fp) checks if the end of file has been reached.
  • ferror(fp) checks if an error occurred during file operations.
  • Useful in reading loops.
  • Example:
  • while(!feof(fp)) { ch=getc(fp); }

 

9. fflush() → Clear buffer

  • fflush(fp) forces writing of buffered data to the file.
  • Useful when using output buffering.
  • For stdout, it clears console buffer.
  • Prevents data loss when program crashes.

 

10. fgetpos(), fsetpos() → Get/set file position

  • fgetpos(fp, &pos) stores current position in pos.
  • fsetpos(fp, &pos) sets the file pointer to saved position.
  • Provides portable file positioning across platforms.
  • Useful in structured file reading.

 

11. sprintf(), snprintf() → Write formatted data into string

  • sprintf() writes formatted output into a string instead of a file.
  • snprintf() does the same but prevents buffer overflow by limiting characters.
  • Example:
  • char str[50];
  • sprintf(str, "Value = %d", 10);

 


 

12. vsprintf(), vsnprintf() → Variadic versions of sprintf

  • These are like sprintf/snprintf but accept variable argument lists.
  • Used with functions like va_list.
  • Safer when writing library functions.
  • Example: logging frameworks.

 

13. vfscanf() → Scan input with variable arguments

  • Similar to fscanf(), but takes variable arguments using va_list.
  • Useful in generic input processing functions.
  • Allows flexible parsing of file data.
  • Example: custom format scanners.

 

14. setbuf(), setvbuf() → Set file buffering

  • setbuf(fp, buffer) sets a buffer for file stream.
  • setvbuf(fp, buffer, mode, size) gives more control (modes: full, line, none).
  • Helps optimize file I/O performance.
  • Example: large file reading efficiency improvement.
  • Files support Input (reading) and Output (writing) operations.
  • Reading: fscanf(fp,"%d",&x); → reads from file.
  • Writing: fprintf(fp,"%d",x); → writes to file.
  • Binary I/O: fread(), fwrite().
  • Allows structured data storage.
  • Handles large datasets efficiently.
  • Avoids memory loss after program ends.
  • Example: Reading student records from a file.
  • Used in applications like banking, hospital management, OS logs.

 

 

 

 

 

 

 

 

 

 

 

Thank You

:: Any Query ::

Contact: Ruparel Education Pvt. Ltd.

Mobile No: 7600044051