C Unit 5 notes
C Unit 5 notes
1. Definition of Files
In C, files are managed using file pointers, which are created using
the FILE type. File operations like reading, writing, and closing are
carried out using various file handling functions.
When opening a file, you must specify the mode in which the file
is to be opened. The mode determines how the file will be
accessed (read, write, append, etc.).
int main() {
FILE *filePtr;
if (filePtr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write to file
fprintf(filePtr, "Hello, File Handling in C!\n");
return 0;
}
3. Standard File Handling Functions
Syntax:
int fclose(FILE *filePtr);
Syntax:
size_t fread(void *ptr, size_t size,
size_t count, FILE *filePtr); ∙ fwrite():
Writes binary data to a file.
Syntax:
size_t fwrite(const void *ptr, size_t size,
size_t count, FILE *filePtr); ∙ fscanf(): Reads
formatted input from a file.
Syntax:
int fscanf(FILE *filePtr, const char *format, ...);
Syntax:
int fprintf(FILE *filePtr, const char *format, ...);
Syntax:
int feof(FILE *filePtr);
Syntax:
int fseek(FILE *filePtr, long int offset, int origin);
∙ ftell(): Returns the current file pointer position.
Syntax:
long int ftell(FILE *filePtr);
Syntax:
void rewind(FILE *filePtr);
4. Random Access to Files
Random access allows you to move the file pointer to any position
within a file for reading or writing. This is done using fseek() and
ftell().
Example:
#include <stdio.h>
int main() {
FILE *filePtr;
char ch;
if (filePtr == NULL) {
printf("File not found!\n");
return 1;
}
fclose(filePtr);
return 0;
}
Example:
#include <stdio.h>
1. Pointer Declaration
Syntax:
dataType *pointerName;
Example:
int *ptr; // Pointer to an integer
2. Pointer Initialization
Example:
int num = 10;
int *ptr = # // Pointer 'ptr' holds the address of 'num'
3. Pointer Arithmetic
Example:
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Points to the first element of the array
printf("%d\n", *ptr); // Outputs 10
ptr++; // Moves to the next element
printf("%d\n", *ptr); // Outputs 20
4. Pointer to Pointer
Example:
int num = 10;
int *ptr1 = #
int **ptr2 = &ptr1; // Pointer to pointer
Example:
int arr[] = {10, 20, 30};
int *ptr = arr;
int main() {
int num = 5;
increment(&num);
printf("%d\n", num); // Outputs 6
return 0;
}
Example of returning pointers from functions:
int* getPointer() {
static int num = 10; // static to ensure the variable
exists outside the function return #
}
int main() {
int *ptr = getPointer();
printf("%d\n", *ptr); // Outputs 10
return 0;
}
Example:
int *arr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5
integers