Module 4
Syllabus:
Pointers - Declaration, Operations on pointers, Passing pointer to a function, Accessing array
elements using pointers, Processing strings using pointers, Pointer to pointer, Array of pointers,
Pointer to function, Pointer to structure, Dynamic Memory Allocation.
Files- Different types of files in C, Opening & Closing a file, Writing to and Reading from a file,
Processing files, Library functions related to file– fseek(), ftell(), fread(), fwrite().
Pointers
● A pointer is a derived data type in C.
● Pointers contain memory addresses as their values. Since these memory addresses are the
locations in the computer memory where program instructions and data are stored,
pointers can be used to access and manipulate data stored in the memory.
● Whenever a variable is declared, the system allocates an appropriate location to hold the
value of the variable. Since every byte has a unique address number, this location will
have its own address.
Consider the statement
int quantity = 179
If the system has chosen address location 5000 for quantity, the value 179 is put in that
location.
The statement
p = &quantity;
assigns the address 5000 to the variable p. The & operator can be remembered as “address of ”
Declaring Pointer Variables
The declaration of pointer variables is done as follows:
data_type *pt_name ;
Since the value of the variable p is the address of the variable quantity, we can access the
value of quantity by using p.
Accessing a Variable through its Pointer
● Once a pointer has been assigned the address of a variable, we can access the value of the
variable using the pointer.
● If p is the address of the variable quantity, *p returns the value of the variable quantity.
● Hence, the following lines of code
int quantity, *p, n;
quantity = 179,
p = &quantity;
n = *p;
will assign the value of the variable quantity to n.
Feature Address-of Operator Dereference / Indirection Operator
(&) (*)
Purpose Gives the address of a variable Gives the value stored at an address
Meaning “Address of” “Value at address”
Usage Used with variables Used with pointer variables
Returns Memory address Actual value
Example p = &a; *p
Role Used to assign address to pointer Used to access or modify value
Null Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you can assign
NULL value. It will provide a better approach.
int *p=NULL;
Operations on pointers
● Address of a variable can be assigned to a pointer variable.
● One pointer variable can be assigned to another pointer variable provided both points
to the items of same datatype.
● A NULL value can be assigned to a pointer variable.
● An integer quantity can be added to or subtracted from a pointer variable. The result
will be a pointer.
● When we increment a pointer, its value is increased by the length of its data type.
● One pointer variable can be subtracted from another pointer variable provided both
points to the elements of the same array. The result will be an integer value.
● Two pointer variables can be compared provided both points to the items of same
datatype.
● A pointer variable can be compared with NULL values.
Write a program to find the sum of two numbers using pointers
#include<stdio.h>
int main()
{
int x,y,sum,*xp,*yp;
printf("Enter value of x:");
scanf("%d",&x);
printf("Enter value of y:");
scanf("%d",&y);
xp=&x;
yp=&y;
sum=*xp+*yp;
printf(" Sum is %d \n",sum);
return 0;
}
OUTPUT
Enter value of x:10
Enter value of y:20
Sum is 30
Write a program to swap two variables using pointers
include<stdio.h>
void main()
{
int x=10,y=20, temp,*a,*b;
printf("\nBefore Swapping");
printf("\nValue of x is %d",x); //output 10
printf("\nValue of y is %d ",y); //output 20
a=&x;
b=&y;
temp= *a;
*a= *b;
*b=temp;
printf("\nAfter swapping");
printf("\nValue of x is %d \n",x); //output 20
printf("\nValue of y is %d \n",y); //output 10
}
POINTERS AND ARRAY
● In C programming, name of the array always points to address of the first element of an
array.
● In C, the array name itself acts like a pointer to the first element.
int arr[5] = {1,2,3,4,5};
arr = address of first element → &arr[0]
arr == &arr[0]
Expression Meaning
arr Base address
arr + i Address of ith element
*(arr + i) Value of ith element
Example:
int arr[3] = {10, 20, 30};
Expression Value
arr address of 10
arr+1 address of 20
*(arr+1) 20
Array Access using Pointers
*(arr + i)
#include<stdio.h>
int main()
{
int p[30], i, n;
printf("Enter the size of array: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", p + i);
}
printf("Array Content\n");
for(i = 0; i < n; i++)
{
printf("%d\t", *(p + i));
}
return 0;
}
Write a program to sort the content of an array using pointers
#include<stdio.h>
#include<malloc.h>
void main()
{
int i,n,temp,j;
int *p = malloc(30 * sizeof(int)); // equivalent to int p[30];
printf("Enter the size of array:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(*(p+j) > *(p+j+1))
{
temp = *(p+j);
*(p+j) = *(p+j+1);
*(p+j+1) = temp;
}
}
}
printf("Array Content\n");
for(i=0;i<n;i++)
{
printf("%d\t",*(p+i));
}
}
OUTPUT
Enter the size of array:5
16 7 14 2 5
Array Content
2 5 7 14 16
Processing string using pointers
Instead of array, we can use a pointer:
char *str = "Hello";
str points to the first character of the string.
char *str = "Hello";
while(*str != '\0')
{
printf("%c", *str);
str++;
}
String Length
#include<stdio.h>
int main()
{
char str[] = "Hello";
char *p = str;
int count = 0;
while(*p != '\0')
{
count++;
p++;
}
printf("Length = %d", count);
return 0;
}
Pointer to pointer
A pointer points to an address of another pointer, such a pointer is called pointer to pointer or
double pointers.
● Pointer p2 contains the address of the pointer variable p1, which points to the location
that contains the desired value. This is known as multiple indirections.
● A variable that is a pointer to a pointer must be declared using additional indirection
operator symbols.
Eg: int **p2;
This means that p2 is a pointer to a pointer of type int.
int main()
{
int x, *p1, **p2;
x =100;
p1 = &x;
p2 = &p1;
printf(“%d”, **p2);
}
The above code will display the output as 100.
Array of pointers
An array of pointers is a collection of pointer variables stored in an array, where each pointer
stores the address of another variable.
Syntax:
data_type *array_name[size];
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;
int *arr[3]; // array of pointers
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
for(int i = 0; i < 3; i++) {
printf("Value: %d\n", *arr[i]); // dereferencing
}
return 0;
}
Output:
Value: 10
Value: 20
Value: 30
Example 2:
#include <stdio.h>
int main()
{
int a, b, c;
int *arr[3]; // array of pointers
// Taking input
printf("Enter 3 integers:\n");
scanf("%d %d %d", &a, &b, &c);
// Storing addresses
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
// Display values using pointers
printf("\nValues are:\n");
for(int i = 0; i < 3; i++)
{
printf("%d\n", *arr[i]);
}
return 0;
}
Output:
Values are:
10
20
30
Pointer to structure
A pointer to a structure is a pointer variable that stores the address of a structure variable.
Syntax:
struct structure_name *pointer_name;
We can access members using arrow operator(->)
Example:
#include <stdio.h>
struct Student
{
int id;
float marks;
};
int main()
{
struct Student s1;
struct Student *ptr = &s1;
printf("Enter ID: ");
scanf("%d", &ptr->id);
printf("Enter Marks: ");
scanf("%f", &ptr->marks);
printf("\nID: %d\nMarks: %.2f\n", ptr->id, ptr->marks);
return 0;
}
Output:
Enter ID: 101
Enter Marks: 89.5
ID: 101
Marks: 89.50
Why Use Pointer to Structure?
● Efficient for large structures (no copying)
● Used in functions (call by reference)
● Used in dynamic memory allocation
● Used in data structures (linked list, trees)
Dynamic memory allocation
Dynamic Memory Allocation is the process of allocating memory at runtime (during execution) using
pointers.
Memory is allocated from the heap area, not the stack.
Why DMA is Needed
• When array size is not known at compile time
• To use memory efficiently
• To create flexible data structures (linked list, trees, etc.)
• To resize memory during execution
Memory Areas in C in C
Memory Type Description
Stack Fixed size, automatic allocation
Heap Dynamic, manual allocation (DMA)
There are 4 main functions:
1. malloc()
2. calloc()
3. realloc()
4. free()
malloc() (Memory Allocation)
Definition
Allocates a single block of memory of given size.
💡 Syntax
ptr = (type *) malloc(size);
• Allocates contiguous memory
• Returns pointer to first byte
• Values are uninitialized (garbage)
• Faster than calloc()
Example
int *ptr;
ptr = (int *) malloc(5 * sizeof(int));
Allocates memory for 5 integers
Important
if(ptr == NULL)
→ Always check for allocation failure
calloc() (Contiguous Allocation)
Allocates memory for multiple elements and initializes all to 0
Syntax
ptr = (type *) calloc(n, size);
• Allocates multiple blocks
• Initializes all values to zero
• Slightly slower than malloc()
Example
int *ptr;
ptr = (int *) calloc(5, sizeof(int));
👉 Allocates 5 integers, all set to 0
3. realloc() (Reallocation)
Changes the size of previously allocated memory
Syntax
ptr = (type *) realloc(ptr, new_size);
• Expands or shrinks memory
• Old data is preserved
• May move memory to new location
Example
ptr = (int *) realloc(ptr, 10 * sizeof(int));
Increases size from 5 → 10 elements
Important
• If memory cannot be extended, a new block is created
• Old pointer may become invalid
4. free() (Deallocation)
Releases allocated memory back to system
Syntax
free(ptr);
• Prevents memory leaks
• Makes pointer invalid after freeing
Best Practice
free(ptr);
ptr = NULL;
Comparison Table
Function Purpose Initialization Arguments
malloc() Allocate memory Garbage 1
calloc() Allocate + init Zero 2
realloc() Resize memory Preserves data 2
free() Deallocate memory — 1
• malloc() → fast, no initialization
• calloc() → zero initialized
• realloc() → resize memory
• free() → release memory
Program using malloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int));
if(ptr == NULL)
{
printf("Memory allocation failed");
return 0;
}
printf("Enter elements:\n");
for(i = 0; i < n; i++)
{
scanf("%d", &ptr[i]);
}
printf("Elements are:\n");
for(i = 0; i < n; i++)
{
printf("%d\t", ptr[i]);
}
free(ptr);
return 0;
}
Program using calloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int *) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Memory allocation failed");
return 0;
}
printf("Elements after calloc (initialized to 0):\n");
for(i = 0; i < n; i++)
{
printf("%d\t", ptr[i]);
}
free(ptr);
return 0;
}
3. Program using realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, n, i, new_size;
printf("Enter initial size: ");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int));
printf("Enter elements:\n");
for(i = 0; i < n; i++)
{
scanf("%d", &ptr[i]);
}
printf("Enter new size: ");
scanf("%d", &new_size);
ptr = (int *) realloc(ptr, new_size * sizeof(int));
printf("Enter new elements:\n");
for(i = n; i < new_size; i++)
{
scanf("%d", &ptr[i]);
}
printf("Updated elements:\n");
for(i = 0; i < new_size; i++)
{
printf("%d\t", ptr[i]);
}
free(ptr);
return 0;
}
4. Program showing free() importance
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *) malloc(3 * sizeof(int));
if(ptr == NULL)
{
printf("Allocation failed");
return 0;
}
ptr[0] = 10;
ptr[1] = 20;
ptr[2] = 30;
printf("Before free:\n");
for(int i = 0; i < 3; i++)
{
printf("%d\t", ptr[i]);
}
free(ptr); // memory released
ptr = NULL; // good practice
printf("\nMemory freed successfully");
return 0;
}
FILES
● A file is a collection of related data that a computer treats as a single unit. Computers
store files to secondary storage so that the contents of files remain intact when a
computer shuts down.
● When a computer reads a file, it copies the file from the storage device to memory; when
it writes to a file, it transfers data from memory to the storage device.
● When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates. It is easy to move the data from one computer to
another without any changes.
● C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
● When working with files, you need to declare a pointer of type FILE. This declaration is
needed for communication between the file and the program.
FILE *fp;
where
*fp – file pointer variable
Types of Files
There are two types of files
1. Text files
2. Binary files
Text files
● Text files are the normal .txt files.
● You can easily create text files using any simple text editors such as Notepad. When you
open those files, you'll see all the contents within the file as plain text. It is easy to edit or
delete the contents.
● They take minimum effort to maintain, are easily readable, and provide the least security
and takes bigger storage space.
Binary files
● Binary files are mostly the .bin files in the computer.
● Instead of storing data in plain text, they store it in the binary form (0's and 1's).
● They can hold a higher amount of data, are not readable easily, and provides better
security than text files
File operations in C
File operations in C are used to store data permanently in files and retrieve it when required
using file handling functions.
The different file operations are:
1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing a file
Naming a file
Three components are of naming a file are:
1. Primary name
2. Period (.)
3. extension
Eg: [Link]
Opening a file
● A file must be “opened” before it can be used. Opening a file is performed using the
fopen() function defined in the stdio.h header file.
● The syntax for opening a file in standard I/O is:
FILE *fp;
fp = fopen("filename","mode");
○ fp is declared as a pointer to the data type FILE.(C has a special "data type" for
handling
○ files which is defined in the standard library 'stdio.h'.) It is called the file pointer
and has the syntax FILE*.
○ filename is a string - specifies the name of the file.
○ fopen returns a pointer to the file which is used in all subsequent file operations.
File opening modes
File Location
● We can provide the relative address of the file location or absolute address of the file.
● Consider your working directory is C:\CP\Test\ .
● Now you want to open a file hello.c in read mode. Two ways to provide the file location
are as given below:
fp =fopen("hello.c","r");
OR
fp = fopen("C:\\CP\\Test\\hello.c","r")
Reading data from a file
● To read the file’s contents from memory, there exists functions like fgetc(), fgets() and
fscanf().
● fgetc() is used to read a character from a file. It reads a single character at a time.
Syntax:
char_variable = fgetc(file_pointer);
Eg: ch=fgetc(fp);
● fgets() reads lines from a file into character arrays.
Syntax:
fgets(str,n,fp);
where
str is pointer to an array of character where the string to read is stored
n is maximum number of characters to be read
fp is pointer to a FILE object that identifies the stream where characters are read from
Eg: fgets(str,60,fp)
● fscanf() reads formatted input
Syntax:
fscanf(stream,”control string”,arg1,arg2,…..);
where
stream is file pointer
control string is the format specifiers
arg1,arg2 … are the arguments
Eg: fscanf(fp,”%d%f%s”,&s1,&s2,s3);
Writing data to a file
● To write data to a file, functions like fputc(), fputs(), fprintf() and fwrite() are used.
1. fputc()
fputc() is used to write a single character to a file. It writes one character at a time.
Syntax:
fputc(char, file_pointer);
Eg: fputc('A', fp);
2. fputs()
fputs() writes a string (line) to a file.
Syntax:
fputs(str, fp);
where
● str is the string to be written
● fp is pointer to a FILE object
Eg: fputs("Hello", fp);
3. fprintf()
fprintf() writes formatted output to a file.
Syntax:
fprintf(file_pointer, "control string", arg1, arg2, ...);
where
● file_pointer is the file pointer
● control string contains format specifiers
● arg1, arg2... are variables
Eg: fprintf(fp, "%d %f %s", a, b, str);
Closing a file
● The file (both text and binary) should be closed after reading/writing.
● Closing a file is performed using the fclose() function.
fclose(fp);
Here, fp is a file pointer associated with the file to be closed.
● fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file.
● This EOF is a constant defined in the header file stdio.h.
File handling functions in C
1. rewind()
2. fseek()
3. ftell()
4. feof()
5. fread()
6. fwrite()
rewind()
rewind() is used to move the file pointer to the beginning of the file.
Syntax:
rewind(fp);
fseek()
fseek() is used to move the file pointer to a specific location in a file. It allows random access,
meaning you can read/write data at any position instead of sequentially.
Syntax:
fseek(fp, offset, position);
fp
● Pointer to the file
offset
● Number of bytes to move the pointer
● Can be positive or negative
origin (starting point)
● SEEK_SET → Beginning of file
● SEEK_CUR → Current position
● SEEK_END → End of file
Example:
fseek(fp, 6, SEEK_SET);
fseek(fp, 3, SEEK_CUR);
fseek(fp, -3, SEEK_END);
Assume the file contains:
"HELLO WORLD"
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9 10
Function Call New position Pointer Moves To Character
fseek(fp, 6, SEEK_SET); 0+6=6 Index 6 W
fseek(fp, 3, SEEK_CUR); 2+3=5 Index 5 space
Assume pointer is at
index 2 (L)
fseek(fp, -3, SEEK_END); 10-3=7 Index 7 O
ftell()
ftell() returns the current position of the file pointer.
ftell(fp);
● ftell() function can be used to get the total size of the file after moving the file pointer at
the end of file
● SEEK_END can be used with the fseek() function to move the file pointer at the end of
the file
fseek(fp, 0, SEEK_END); // Move to end
length = ftell(fp); // Get file size
feof()
feof() checks whether the end of file (EOF) has been reached.
Syntax:
feof(fp);
fread()
fread() is used to read binary data from a file into memory. It is commonly used for reading
arrays, structures, or binary files.
Syntax:
fread(*ptr,size,nmemb,fp)
ptr → Pointer to memory where data will be stored
size → Size of each element (in bytes)
nmemb → Number of elements to read
fp → Pointer to the file
Example:
int arr[5];
fread(arr, sizeof(int), 5, fp);
● arr[5] → creates an array of 5 integers in memory.
● fread(arr, sizeof(int), 5, fp);
This reads 5 integers from the file fp and stores them in arr.
● sizeof(int) → size of one integer (usually 4 bytes)
● 5 → number of integers to read
So, total bytes read = 5 × sizeof(int) = 20 bytes (if int = 4 bytes).
fwrite()
fwrite() is used to write binary data from memory into a file. It is commonly used for
arrays, structures, or binary files.
Syntax:
fwrite(*ptr,size,nmemb,fp)
ptr → Pointer to memory containing data to write
size → Size of each element (in bytes)
nmemb → Number of elements to write
fp → Pointer to the file
Example:
int arr[5] = {1,2,3,4,5};
fwrite(arr, sizeof(int), 5, fp);
● arr → pointer to the first element
● sizeof(int) → size of one element (4 bytes)
● 5 → number of elements to write
Writes 20 bytes (5 × 4) from memory to the file pointed by fp.
File Access Methods in C
There are two main ways to access files:
1. Sequential Access
2. Random (Direct) Access
Sequential Access Files
In sequential access, data in a file is read or written one after another in order,
from beginning to end.
Features
✔ Data is processed line by line / record by record
✔ Cannot skip directly to a specific position
✔ Simple and easy to use
✔ Suitable for text files
Example
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
while((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
}
fclose(fp);
return 0;
}
Real-Life Example
Reading a book from page 1 to last page
Advantages
● Simple
● Less memory usage
Disadvantages
● Slow if you want specific data
● Cannot jump directly
Random Access Files
In random access, data can be accessed directly at any position in the file without
reading previous data.
Features
✔ Direct access using file position
✔ Faster for large files
✔ Uses functions like fseek(), ftell(), rewind()
✔ Suitable for binary files / records
Example
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("[Link]", "r");
fseek(fp, 5, SEEK_SET); // move to 5th byte
char ch = fgetc(fp);
printf("Character at position 5: %c\n", ch);
fclose(fp);
return 0;
}
Real-Life Example
Jumping directly to a specific page in a book
Advantages
● Fast access to any position
● Efficient for large data
Disadvantages
● Slightly complex
● Requires proper position handling
File Programs
Write a program to display the content of a file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("[Link]","r");
while(feof(fp) == 0)
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
}
Content of [Link]
Hello, Welcome to C Programming Lectures.
OUTPUT
Hello, Welcome to C Programming Lectures.
Write a program to count number of vowels in a given file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int countV=0;
fp = fopen("[Link]","r");
while(feof(fp) == 0)
{
ch=fgetc(fp);
if(ch == 'a' || ch == 'A' || ch=='e' ||ch=='E' || ch == 'I' || ch == 'i' ||ch == 'O'
||ch=='o'||ch == 'U' ||ch == 'u')
{
countV++;
}
printf("Count of Vowels=%d",countV);
}
fclose(fp);
}
Content of [Link]
Hello, Welcome to C Programming Lectures.
OUTPUT
Count of Vowels=12
Write a program to copy the content of one file to another.
#include<stdio.h>
void main()
{
FILE *f1,*f2;
char ch;
f1 = fopen("[Link]","r");
f2 = fopen("[Link]","w");
while(feof(f1) == 0)
{
ch=fgetc(f1);
fputc(ch,f2);
}
printf("Successfully Copied");
fclose(f1);
fclose(f2);
}
Content of [Link]
Hello, Welcome to C Programming Lectures.
OUTPUT
Successfully Copied
Content of [Link]
Hello, Welcome to C Programming Lectures.
Write a program to merge the content of two files.
#include<stdio.h>
void main()
{
FILE *f1,*f2,*f3;
char ch;
f1 = fopen("[Link]","r");
f2 = fopen("[Link]","r");
f3 = fopen("[Link]","w");
while(feof(f1) == 0)
{
ch=fgetc(f1);
fputc(ch,f3);
}
while(feof(f2) == 0)
{
ch=fgetc(f2);
fputc(ch,f3);
}
printf("Successfully Merged");
}
Content of [Link]
Hello, Welcome to C Programming Lectures.
Content of [Link]
C is very easy to learn.
OUTPUT
Successfully Merged
Content of [Link]
Hello, Welcome to C Programming Lectures. C is very easy to learn.
Write a program to read numbers from a file and display the largest number.
#include<stdio.h>
void main()
{
FILE *f1;
int large,num;
f1 = fopen("[Link]","r");
fscanf(f1,"%d",&large); // setting first element as largest element
while(feof(f1) == 0)
{
fscanf(f1,"%d",&num);
if(large<num)
{
large= num;
}
}
fclose(f1);
printf("Largest element = %d",large);
}
Content of [Link]
15 21 7 29 36 78 67 56 10
OUTPUT
Largest element = 78
Consider you are a content writer in Wikipedia. You are the person who write the known
facts about APJ Abdul Kalam. After his death, you need to change all is to was. Write a
program to replace all is’ to was’ to a new file.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
char str[30];
f1 = fopen("[Link]","r");
f2 = fopen("[Link]","w");
fscanf(f1,"%s",str);
while(feof(f1) == 0)
{
if(strcmp(str,"is")==0)
fprintf(f2,"was");
else
fprintf(f2,"%s ",str);
fscanf(f1,"%s",str);
}
fclose(f1);
fclose(f2);
printf("Replaced String Successfully\n");
}
Content of [Link]
APJ Abdul Kalam is the missile man
OUTPUT
Replaced String Successfully
Content of [Link]
APJ Abdul Kalam was the missile man
Write a program to reverse each content of file to another.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
char str[30],rev[30];
int i,j;
f1 = fopen("[Link]","r");
f2 = fopen("[Link]","w");
while(feof(f1) == 0)
{
fscanf(f1,"%s",str);
j=0;
for(i=strlen(str)-1;i>=0;i--)
{
rev[j]=str[i];
j++;
}
rev[j]='\0';
fprintf(f2,"%s ",rev);
}
fclose(f1);
fclose(f2);
}
Content of [Link]
Welcome to C programming
Content of [Link] after execution
emocleW ot C gnimmargorp
Write a program to count number of words and lines in a file.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
int countW=0,countL=0;
char ch;
f1 = fopen("[Link]","r");
while (feof(f1) == 0 )
{
ch = fgetc(f1);
if(ch == ' ' || ch == '\t' || ch == '\n')
countW++;
if(ch == '\n')
countL++;
}
printf("Count of words = %d\n",countW);
printf("Count of Lines = %d",countL);
fclose(f1);
}
Write a program to append some data to already existing file.
#include<stdio.h>
void main()
{
FILE *f1;
char str[30];
f1 = fopen("[Link]","a");
printf("Enter the string:");
fgets(str, sizeof(str), stdin);
fprintf(f1,"%s",str);
fclose(f1);
}
Write a program to display content of a file two times without closing the file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("[Link]","r");
while(feof(fp)==0)
{
ch=fgetc(fp);
printf("%c",ch);
}
rewind(fp);
while(feof(fp)==0)
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
}
OUTPUT
Hello, Welcome to C programming. Hello, Welcome to C programming.
Write a program to read the details of “n” Employees with following fields – name, empid
and salary and write the details into a file. Then read details from file and display the name
of employee who has highest salary.
#include<stdio.h>
struct Employee
{
char name[30];
int empid;
double salary;
};
void main()
{
FILE *fp;
struct Employee e[10],res,temp;
int i,n;
fp = fopen("[Link]","w");
printf("Enter the limit:");
scanf("%d",&n);
printf("Enter the details of Employee\n");
for(i=0;i<n;i++)
{
printf("Name:");
scanf("%s",e[i].name);
printf("EmpId:");
scanf("%d",&e[i].empid);
printf("Salary:");
scanf("%lf",&e[i].salary);
fwrite(&e[i],sizeof(e[i]),1,fp);
}
fclose(fp);
fp = fopen("[Link]","r");
[Link]=-1.0;
while(feof(fp) == 0)
{
fread(&temp,sizeof(temp),1,fp);
if([Link] < [Link])
{
res = temp;
}
}
printf("Name of Employee with highest Salary:%s",[Link]);
}
OUTPUT
Enter the limit:2
Enter the details of Employee
Name:John
Salary:10000
Name:Kiran
EmpId:102
Salary:20000
Name of Employee with highest Salary:Kiran