Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Wednesday, March 15, 2023

C program to decrypt a text file using Caesar Cipher

Caesar Cipher File Decryptor


This C program will decrypt a given text file into plain text file using Caesar Cipher cryptographic algorithm.


#include <stdio.h>
#define MAX_FILE_SIZE 1000

//function to decrypt message based on given key
void decrypt(char *message, int key) {
    char ch;
    int i;
    for(i = 0; message[i] != '\0'; ++i){
        ch = message[i];
        if(ch >= 'a' && ch <= 'z'){
            ch = ch - key;
            if(ch < 'a'){
                ch = ch + 'z' - 'a' + 1;
            }
            message[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = ch - key;
            if(ch < 'A'){
                ch = ch + 'Z' - 'A' + 1;
            }
            message[i] = ch;
        }
    }
}

int main() {
    FILE *fileIn, *fileOut;
    char message[MAX_FILE_SIZE];
    int key;

    // Open the encrypted file
    fileIn = fopen("demo1.txt", "r");
    if(fileIn == NULL){
        printf("File open error.\n");
        return 0;
    }

    // Read the encrypted message from given file
    fgets(message, MAX_FILE_SIZE, fileIn);

    // Close the input file
    fclose(fileIn);

    // Prompt user to enter the key
    printf("Enter key: ");
    scanf("%d", &key);

    // Decrypt the message
    decrypt(message, key);

    // Open the output file
    fileOut = fopen("decrypted.txt", "w");
    if(fileOut == NULL){
        printf("File write error.\n");
        return 0;
    }

    // Write the decrypted message to output file
    fprintf(fileOut, "%s", message);

    // Close the output file
    fclose(fileOut);

    printf("File decrypted successfully.\n");

    return 0;
}

Sunday, January 12, 2020

Write a student data into a file using the C Structure

File Management using C Structure

This C Program will write a student data into a file using the Structure and File Management concept of C programming.

Source Code

#include <stdio.h>
//Structure to store student data.
struct student
{
   char fname[30];
   char lname[30];
   int  rollno;
   float percentage;
};

void main ()
{
   FILE *fp;
   //declare structure(student) variable
   struct student input;
   // open student file for writing
   fp = fopen ("student.dat","w");
   if (fp == NULL){
      printf("\nFile opening error..\n\n");
      exit (1);
     }

   printf("Enter \"exit\" as First Name to stop reading user input.");

   while (1)
     {
      printf("\nFirst Name: ");
      scanf ("%s", input.fname);
     
      if (strcmp(input.fname, "exit") == 0)
         exit(1);
     
      printf("Last Name : ");
      scanf ("%s", input.lname);
      printf("Roll Number  : ");
      scanf ("%d", &input.rollno);
      printf("Percentage : ");
      scanf ("%f", &input.percentage);

      // write student data to student.dat  file
      fwrite (&input, sizeof(struct student), 1, fp);
     }
}

Output of program 

Enter "exit" as First Name to stop reading user input.
First Name: K
Last Name : Patel
Roll Number  : 101
Percentage : 90.50

First Name: ABC
Last Name : Shah
Roll Number  : 102
Percentage : 95.50

First Name: exit

* * * * *


< Read more about C File Management >

< Read more about C Structure >

< Back to Home Page>



Thursday, October 25, 2018

Updating File Data using fseek


File Management - Updating File Records


Following program will allow us to change marks of roll no. 101 using fseek() function. Content of "student.txt" (RollNo, Marks, Name) file is as under:

101 50 AAA
102 60 BBB
103 65 CCC

#include <stdio.h>

int main () {
   FILE *fp;
   char str[80];
   int newmarks;
   
   fp = fopen("student.txt","r+");

   printf("Original File Data:\n");
   while(fgets(str,80,fp)!=NULL)
    printf("%s", str);
   //getch();
   
   printf("\n\nEnter new marks of Roll no. 101:");
   scanf("%d", &newmarks);
      
   printf("Updated File Data:\n\n");
   
   itoa(newmarks,str, 10); //convert int to string; fputs() write "string" to fp
   
   fseek(fp, 4, 0); //set the pointer to position no. 4
   
   fputs(str, fp);  //write string to current position of fp
   fclose(fp);
   
   fp = fopen("student.txt","r");

   while(fgets(str,80,fp)!=NULL)
    printf("%s", str);
   
   fclose(fp);
   getch();
   return(0);
}


Output of Program

Original File Data:
101 55 AAA
102 60 BBB
103 65 CCC

Enter new marks of Roll no. 101:75

Updated File Data:
101 75 AAA
102 60 BBB
103 65 CCC

Saturday, September 22, 2018

Count vowels in given file.


C Program to count Vowels in a given file.

This program will read input from "data.txt" file and prints total number of vowels.

#include<stdio.h>
int main()
{
  FILE *fp;
  char ch;
  int cnt=0;

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

  if (fp == NULL)
  {
  printf("Can't Open File.");
  exit(1);
  }
  printf("File content is : ");
  ch = fgetc(fp);
  
  while(ch != EOF)
  {
    putchar(ch);
if( ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
        cnt++;
    ch = fgetc(fp);
  }

  printf("\n\nTotal vowels in given file = %d",cnt);
  return 0;
}

Output of Program

File content is : THIS IS TOP C PROGRAMMING PRACTICALS BLOG.

Total vowels in given file = 10


Thursday, March 29, 2018

List Files in Directory


Following C Program will display the List of Files present in current directory. This C program is stored in D:\\CProgramPracticals\ directory; hence it will display all files stored in this directory.

Program to Display List of Files in Current Directory

#include <stdio.h>
#include <dirent.h> 
int main()
{
    DIR *my_dir;
    struct dirent *temp_dir;
    my_dir = opendir(".");
    if (my_dir)
    {
        while ((temp_dir = readdir(my_dir)) != NULL)
        {
            printf("%s\n", temp_dir->d_name);            
        }
        closedir(my_dir);
    }
    return 0;
}



Output of Program

.
..
Armstrong-number.c
bell-using-ascii-7.c
bitcoin_profitloss.c
bitcoin_profitloss.exe
blink.c
cprogrampracticals.h
digitsToWords.c
digitsToWords.exe
EMICalulator.c
EMICalulator.exe
leapYear.c
leapYear.exe
LifeInsurancePremiumCalculator.c
LifeInsurancePremiumCalculator.exe
piano.c
ReadIPAddress.c
ReadIPAddress.exe
StockBroker.c
StockClientBill.c
StockClientBill.exe
swap-variable.c
SystemDateTime.c


Tuesday, November 28, 2017

Split file into 3 equal files.

C++ Program to Split file into 3 equal files.

This program will take input from data.txt file and split it into 3 equal size files (data1.txt, data2.txt, data3.txt).


#include<iostream>
#include<fstream>

using namespace std;
int main()
{
ifstream fin;
ofstream fout1, fout2, fout3;
char ch;
int i, cnt=0, equal_part=0, last_part=0;
fin >> std::noskipws;

fin.open("data.txt");
if(!fin){  
    cout<<"Error Open Error."; exit(1); 
}

//logic to count total character in input data file
while(fin.eof()==0){
fin >> ch;
cnt++;
}
cout << "Total characters in data.txt file = "<< cnt-1 << endl;
fin.close();
//logic to divide no. characters in each file
equal_part = (cnt-1)/3;
last_part = (cnt-1)%3;
cout <<"Total files to be created=3."<< endl;
cout << "Each output file contains: "<<equal_part <<" characters."<<endl;
cout << "Last output file contains: "<<equal_part+last_part<<" characters."<<endl;

fin.open("data.txt");
fin >> std::noskipws;

fout1.open("data1.txt");
if(!fout1){ 
cout<<"File data1.txt Open Error.";  exit(1);
}
for(i=0; i<equal_part; i++) {
fin >> ch;
fout1 << ch;
}

fout2.open("data2.txt");
if(!fout2){ 
cout<<"File data2.txt Open Error.";  exit(1);
}

for(i=0; i<equal_part; i++)
{
fin >> ch;
fout2 << ch;
}

fout3.open("data3.txt");
if(!fout3){ 
cout<<"File data3.txt Open Error.";  exit(1);
}
for(i=0; i<equal_part+last_part; i++)
{
fin >> ch;
fout3 << ch;
}

fin.close();
fout1.close();
fout2.close();
fout3.close();

return 0;
}

Output of program

Total characters in data.txt file = 10
Total files to be created=3.
Each output file contains: 3 characters.
Last output file contains: 4 characters.

Tuesday, November 21, 2017

C++ Program to copy files.

#include<iostream>
#include<fstream>

using namespace std;
int main()
{
ifstream fin;
ofstream fout;
char ch, fname1[20], fname2[20];

fin >> std::noskipws; //To copy whitespace characters

cout<<"Enter source file name: ";
gets(fname1);
fin.open(fname1);

if(!fin){
cout<<"Error Open Error.";
exit(1);
}

cout<<"Enter target file name: ";
gets(fname2);
fout.open(fname2);

if(!fout){
cout<<"File Open Error.";
exit(1);
}
//Logic to copy data from file1 to file2
while(fin.eof()==0){
fin >> ch;
fout << ch;
}
cout<<"File content copied successfully...";

fin.close();
fout.close();
return 0;
}

Output of program

Enter source file name: file1.txt
Enter target file name: file2.txt
File content copied successfully...

Friday, November 17, 2017

C++ File Operations on Binary Files

This C++ file management program will append data into a binary file.
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
class student
{
  int rollno;
  char name[20];
  char dept[10];

  public:
void getdata()
{
cout << "Rollno: ";
cin >> rollno;

cout << "Name: ";
cin >> name;

cout << "Branch: ";
cin >> dept;
}
};

int main()
{
  student s1;
  char ans='y';

  ofstream fout("student.txt", ios::app);

  while(ans=='y' || ans=='Y')
  {
s1.getdata();
fout.write((char *)&s1, sizeof(s1));
cout<<"Data appended in file successfully.\n";
cout<<"\nWant to add more data? (y/n)..";
cin>>ans;
  }

  fout.close();
  return 0;
}

Output of program:

Rollno: 101
Name: Amit
Branch: MCA
Data appended in file successfully.

Want to add more data? (y/n)..y
Rollno: 102
Name: Sunit
Branch: PhD
Data appended in file successfully.

Want to add more data? (y/n)..n

Tuesday, November 14, 2017

Use of fprintf and fscanf

File management: Program to demonstrate use of fprintf() and fscanf() function. This program will read a word from keyboard and write it into a data.txt file. After closing a file, program will again open it and get a word from file and display on screen.



#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp;
  char str[80], str1[80];

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

  if(fp == NULL)
  {
printf("Cannot open file.\n");
exit(1);
  }
  printf("Enter string to be written in a file: ");
  fscanf(stdin, "%s", str); /*Read from keyboard */

  fprintf(fp, "%s", str); /*Write str to file */
  fclose(fp);

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

  if(fp == NULL) {
printf("Cannot open file.\n");
exit(1);
  }
  fscanf(fp, "%s", str1); /* read a word from file and copy into str1 */
  fprintf(stdout, "%s", str1); /* print str1 on screen */
  return 0;
}

Output of program

Enter string to be written in a file: Hello
Hello

Sunday, October 15, 2017

Read one word from a file.



Following C++ program will read a word from data.txt file stored in the same location where source program is stored.

#include <fstream>
#include <iostream>
using namespace std;
int main () {   
   char word[20];

   ifstream fin;    //open file to read.
   fin.open("data.txt");
 
   cout << "Reading a word from a file...\n";
   
   fin >> word;
   cout << word;    //write data to screen.
 
   fin.close();     //close the opened file.
   return 0;
}

Output of program

Reading a word from a file...
hello



Wednesday, May 10, 2017

fopen() validation

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp = fopen("input.txt", "w");
    if (fp == NULL)
    {
        printf("File open error..");
        exit(0);
    }
    else
    {
        printf("File opened successfully..", fp);
        //Add your C File Management logic here.
    }
    fclose(fp);
    return 0;
}

Output of program

File opened successfully..

Saturday, March 25, 2017

C program to append data to text file.

This C program will add message entered by user into the data.txt file. Note that, present content will remain as it is, and new content will be appended at the bottom of data.

#include <stdio.h>
#include <string.h>
int main()
{
   FILE *fp;
   char str[80];
 
   fp = fopen("data.txt", "a");
 
   printf("Enter your message:");
   gets(str);
 
   fprintf(fp, "%s",str);
 
   printf("Your message is appended in data.txt file.");
   fclose(fp);
   //File validation is to be added..
   return 0;
}


Output of program

Enter your message:How are you?
Your message is appended in data.txt file.

Original content of data.txt file is: Hello student.

After execution of program, content of data.txt file: Hello student. How are you?

Friday, March 24, 2017

Program to read and print test.txt file.

This C program will read content from a test.txt file and print it on a screen.

#include<stdio.h>
int main(){

 FILE *fp, *fopen();
 char str1[80], ch;

 fp = fopen("test.txt","r");
 ch = fgetc(fp);

 while(ch != EOF)
 {
  printf("%c",ch);  
  ch=fgetc(fp);
 }
 fclose(fp);
 return 0;
}

Output of the program

Hello Student,
This content is from test.txt file.

Saturday, June 18, 2016

C program to delete a given file.

NOTE: Be careful while executing following program. This program will delete file which you enter at run time.

C program to delete a given file.


#include<stdio.h>
int main()
{
   int file_check_flag;
   char file_name[30];
   printf("Enter file name to be deleted:\n");

   gets(file_name);

   file_check_flag = remove(file_name);

   if( file_check_flag == 0 )
      printf("Your file %s is deleted successfully.\n",file_name);
   else
      printf("Unable to delete %s file.\n",file_name);
   return 0;
}

Output of program

Enter file name to be deleted:

mydata.txt

Your file mydata.txt is deleted successfully.


Thursday, March 31, 2016

C program to implement receiver side confidentiality.

//Assumption: test1.txt is encrypted using Ceasar cipher (Key=3).

#include<stdio.h>
int main() {
 
   FILE *fp1, *fp2;
   char a;

   fp1 = fopen("test1.txt", "r");
 
   if (fp1 == NULL) {
      puts("cannot open test.txt file.");
      exit(1);
   }

   fp2 = fopen("test2.txt", "w");
 
   if (fp2 == NULL) {
      puts("Not able to test1.txt file.");
      fclose(fp1);
      exit(1);
   }

   a = fgetc(fp1);
   fprintf(fp2,"%c",a-3);

   while(a != EOF)
   {
    a = fgetc(fp1);
    fprintf(fp2,"%c",a-3);
   }
 
  printf("test1.txt is successfully decrypted and stored to test2.txt.");
  printf("\nUser can read test2.txt file.");
 
  fclose(fp1);
  fclose(fp2);
  return 0;
}
/*Output of program:
test1.txt is successfully decrypted and stored to test2.txt.
User can read test2.txt file.
*/

C program to implement sender side confidentiality.

//Create test.txt file with some text in the same folder where you are saving this program.

#include<stdio.h>

int main() {
 
   FILE *fp1, *fp2;
   char a;

   fp1 = fopen("test.txt", "r");
 
   if (fp1 == NULL) {
      puts("cannot open test.txt file.");
      exit(1);
   }

   fp2 = fopen("test1.txt", "w");
 
   if (fp2 == NULL) {
      puts("Not able to test1.txt file.");
      fclose(fp1);
      exit(1);
   }

   a = fgetc(fp1);
   fprintf(fp2,"%c",a+3);

   while(a != EOF)
   {
    a = fgetc(fp1);
    fprintf(fp2,"%c",a+3);
   }
 
  printf("test.txt is successfully encrypted and stored to test1.txt.");
  printf("\ntest1.txt can be forwarded to destination.");
 
  fclose(fp1);
  fclose(fp2);
  return 0;
}

/*Output of program
test.txt is successfully encrypted and stored to test1.txt.
test1.txt can be forwarded to destination.
*/

Wednesday, March 23, 2016

C program to copy content of one file to other.

#include<stdio.h>
int main() {
   FILE *fp1, *fp2;
   char a;

   fp1 = fopen("test.txt", "r");
   if (fp1 == NULL) {
      puts("cannot open test.txt file.");
      exit(1);
   }

   fp2 = fopen("test1.txt", "w");
   if (fp2 == NULL) {
      puts("test1.txt file error.");
      fclose(fp1);
      exit(1);
   }

   do {
      a = fgetc(fp1);
      fputc(a, fp2);
   } while (a != EOF);
  printf("test.txt is successfully copied to test1.txt.");
  fclose(fp1);
  fclose(fp2);
  return 0;
}

Output of the program

test.txt is successfully copied to test1.txt.


Monday, February 15, 2016

C program to write a word in text file.

#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char str[80];
fp = fopen("test.txt", "w+");
printf("Enter your message:");
gets(str);
fprintf(fp, "%s",str);
printf("Your message is written in test.txt file.");
fclose(fp);
//File validation is to be performed...
   return 0;
}


Output of program

Enter your message:hello student
Your message is written in test.txt file.


Monday, January 25, 2016

C program to read file line by line.

This program will read and print content of the "test.txt" file. 

Note: Save source code (.c) file and "test.txt" file in same folder.

#include<stdio.h> 
int main()
{
 FILE *f1, *fopen();
 char str1[80];
 
 f1 = fopen("test.txt","r");

 while(fgets(str1,80,f1)!=NULL)
 {
  printf("%s",str1); 
 }
 fclose(f1);
 return 0;
}