Thursday 16 May 2013

C Program remove spaces, blanks from a string


C code to remove spaces or excess blanks from a string, For example consider the string
"c  programming"
There are two spaces in this string, so our program will print a string
"c programming". It will remove spaces when they occur more than one time consecutively in string anywhere.

C programming code

#include <stdio.h>
 
int main()
{
   char text[100], blank[100];
   int c = 0, d = 0;
 
   printf("Enter some text\n");
   gets(text);
 
   while (text[c] != '\0')
   {
      if (!(text[c] == ' ' && text[c+1] == ' ')) {
        blank[d] = text[c];
        d++;
      }
      c++;
   }
 
   blank[d] = '\0';
 
   printf("Text after removing blanks\n%s\n", blank);
 
   return 0;
}
If you want you can copy blank into text string so that original string is modified.
Download Remove spaces program.

C Program to find frequency of characters in a string


This program computes frequency of characters in a string i.e. which character is present how many times in a string. For example in the string "code" each of the character 'c', 'o', 'd', and 'e' has occurred one time. Only lower case alphabets are considered, other characters (uppercase and special characters) are ignored. You can easily modify this program to handle uppercase and special symbols.

C programming code

#include <stdio.h>
#include <string.h>
 
int main()
{
   char string[100], ch;
   int c = 0, count[26] = {0};
 
   printf("Enter a string\n");
   gets(string);
 
   while ( string[c] != '\0' )
   {
      /* Considering characters from 'a' to 'z' only */
 
      if ( string[c] >= 'a' && string[c] <= 'z' ) 
         count[string[c]-'a']++;
 
      c++;
   }
 
   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 )
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
 
   return 0;
}
Download Character frequency program.

Anagram in C


C program to check whether two strings are anagrams or not, string is assumed to consist of alphabets only. Two words are said to be anagrams of each other if the letters from one word can be rearranged to form the other word. From the above definition it is clear that two strings are anagrams if all characters in both strings occur same number of times. For example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only one time in both strings. Our algorithm tries to find how many times characters appear in the strings and then comparing their corresponding counts.

C anagram programming code

#include <stdio.h>
 
int check_anagram(char [], char []);
 
int main()
{
   char a[100], b[100];
   int flag;
 
   printf("Enter first string\n");
   gets(a);
 
   printf("Enter second string\n");
   gets(b);
 
   flag = check_anagram(a, b);
 
   if (flag == 1)
      printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
   else
      printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
 
   return 0;
}
 
int check_anagram(char a[], char b[])
{
   int first[26] = {0}, second[26] = {0}, c = 0;
 
   while (a[c] != '\0')
   {
      first[a[c]-'a']++;
      c++;
   }
 
   c = 0;
 
   while (b[c] != '\0')
   {
      second[b[c]-'a']++;
      c++;
   }
 
   for (c = 0; c < 26; c++)
   {
      if (first[c] != second[c])
         return 0;
   }
 
   return 1;
}
Download Anagram program.

C Programming Files

In C programming, file is a place on disk where a group of related data is stored.



Why files are needed?


When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands.

There are large numbers of functions to handle file I/O in C language. In this tutorial, you will learn to handle standard I/O(High level file I/O functions) in C.

High level file I/O functions can be categorized as:
  1. Text file
  2. Binary file

File Operations

  1. Creating a new file
  2. Opening an existing file
  3. Reading from and writing information to a file
  4. Closing a file

Working with file

While working with file, you need to declare a pointer of type file. This declaration is needed for 

communication between file and program.

FILE *ptr;

Opening a file


Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:

ptr=fopen("fileopen","mode")

For Example:
fopen("E:\\cprogram\program.txt","w"); 
  
/* --------------------------------------------------------- */
 E:\\cprogram\program.txt is the location to create file.   
 "w" represents the mode for writing.
/* --------------------------------------------------------- */

Here, the program.txt file is opened for writing mode.

Opening Modes in Standard I/O
File ModeMeaning Of ModeDuring Inexistence Of File
rOpen for reading.If the file does not exist, fopen() returns NULL.
wOpen for writing.If  the file exists, its contents are overwritten. If the file does not exist, it will be created.
aOpen for append. i.e, Data is added to end of file.If the file does not exists, it will be created.
r+Open for both reading and writing.If the file does not exist, fopen() returns NULL. 
w+Open for both reading and writing.If  the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+Open for both reading and appending.If the file does not exists, it will be created.

Closing a File


The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().

fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions.


The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf()and fscanf() is that, the first argument is a pointer to the structure FILE


Writing to a file



#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   fptr=fopen("C:\\program.txt","w");
   if(fptr==NULL){
      printf("Error!");   
      exit(1);             
   }
   printf("Enter n: ");
   scanf("%d",&n);
   fprintf(fptr,"%d",n);   
   fclose(fptr);
   return 0;
}
This program takes the number from user and stores in file. After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open that file, you can see the integer you entered.

Similarly, fscanf()
can be used to read data from file.

Reading from file



#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   if ((fptr=fopen("C:\\program.txt","r"))==NULL){
       printf("Error! opening file");
       exit(1);         /* Program exits if file pointer returns NULL. */
   }
   fscanf(fptr,"%d",&n);
   printf("Value of n=%d",n); 
   fclose(fptr);   
   return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered in that program using this program.

Other functions like fgetchar()fputc() etc. can be used in similar way.



Binary Files


Depending upon the way file is opened for processing, a file is classified into text file and binary file.

If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file is used.

Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to file.

Opening modes of binary files


Opening modes of binary files are rbrb+wbwb+,ab and ab+. The only difference between opening modes of text and binary files is that, b is appended to indicate that, it is binary file
.

Reading and writing of a binary file


Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Function fwrite() takes four arguments, address of data to be written in disk, size of data to be written in disk, number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.

Examples

C program to read a file
C program to read a file: This program reads a file entered by the user and displays its contents on the screen, fopen function is used to open a file it returns a pointer to structure FILE. FILE is a predefined structure in stdio.h . If the file is successfully opened then fopen returns a pointer to file and if it is unable to open a file then it returns NULL. fgetc function returns a character which is read from the file and fclose function closes the file. Opening a file means we bring file from disk to ram to perform operations on it. The file must be present in the directory in which the executable file of this code sis present.

C program to open a file

C programming code to open a file and to print it contents on screen.
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch, file_name[25];
   FILE *fp;
 
   printf("Enter the name of file you wish to see\n");
   gets(file_name);
 
   fp = fopen(file_name,"r"); // read mode
 
   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
 
   printf("The contents of %s file are :\n", file_name);
 
   while( ( ch = fgetc(fp) ) != EOF )
      printf("%c",ch);
 
   fclose(fp);
   return 0;
}
Download Read file program.
C program to copy files
C program to copy files: This program copies a file, firstly you will specify the file to copy and then you will enter the name of target file, You will have to mention the extension of file also. We will open the file that we wish to copy in read mode and target file in write mode.

C programming code

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch, source_file[20], target_file[20];
   FILE *source, *target;
 
   printf("Enter name of file to copy\n");
   gets(source_file);
 
   source = fopen(source_file, "r");
 
   if( source == NULL )
   {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   printf("Enter name of target file\n");
   gets(target_file);
 
   target = fopen(target_file, "w");
 
   if( target == NULL )
   {
      fclose(source);
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   while( ( ch = fgetc(source) ) != EOF )
      fputc(ch, target);
 
   printf("File copied successfully.\n");
 
   fclose(source);
   fclose(target);
 
   return 0;
}
Download File copy program.
C program to merge two files
This c program merges two files and stores their contents in another file. The files which are to be merged are opened in read mode and the file which contains content of both the files is opened in write mode. To merge two files first we open a file and read it character by character and store the read contents in another file then we read the contents of another file and store it in file, we read two files until EOF (end of file) is reached.

C programming code

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   FILE *fs1, *fs2, *ft;
 
   char ch, file1[20], file2[20], file3[20];
 
   printf("Enter name of first file\n");
   gets(file1);
 
   printf("Enter name of second file\n");
   gets(file2);
 
   printf("Enter name of file which will store contents of two files\n");
   gets(file3);
 
   fs1 = fopen(file1,"r");
   fs2 = fopen(file2,"r");
 
   if( fs1 == NULL || fs2 == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      getch();
      exit(EXIT_FAILURE);
   }
 
   ft = fopen(file3,"w");
 
   if( ft == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   while( ( ch = fgetc(fs1) ) != EOF )
      fputc(ch,ft);
 
   while( ( ch = fgetc(fs2) ) != EOF )
      fputc(ch,ft);
 
   printf("Two files were merged into %s file successfully.\n",file3);
 
   fclose(fs1);
   fclose(fs2);
   fclose(ft);
 
   return 0;
}
Download merge files program.
C Program to write all the members of an array of strcures to a file using fwrite(). Read the array from the file and display on the screen.

#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
    struct s a[5],b[5];   
    FILE *fptr;
    int i;
    fptr=fopen("file.txt","wb");
    for(i=0;i<5;++i)
    {
        fflush(stdin);
        printf("Enter name: ");
        gets(a[i].name);
        printf("Enter height: "); 
        scanf("%d",&a[i].height); 
    }
    fwrite(a,sizeof(a),1,fptr);
    fclose(fptr);
    fptr=fopen("file.txt","rb");
    fread(b,sizeof(b),1,fptr);
    for(i=0;i<5;++i)
    {
        printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
    }
    fclose(fptr);
}
C Program to read name and marks of n number of students from user and store them in a file. If the file previously exits, add the information of n students.

#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","a"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}
C Program to read name and marks of students and store it in file


#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","w"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}
C Program to read name and marks of students and store it in file


#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","w"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}
C Program to delete a file

This c program deletes a file which is entered by the user, the file to be deleted should be present in the directory in which the executable file of this program is present. Extension of the file should also be entered, remove macro is used to delete the file. If there is an error in deleting the file then an error will be displayed using perror function.

C programming code

#include<stdio.h>
 
main()
{
   int status;
   char file_name[25];
 
   printf("Enter the name of file you wish to delete\n");
   gets(file_name);
 
   status = remove(file_name);
 
   if( status == 0 )
      printf("%s file deleted successfully.\n",file_name);
   else
   {
      printf("Unable to delete the file\n");
      perror("Error");
   }
 
   return 0;
}
Download Delete file program executable.

C Program to generate random numbers


This c program generates random numbers using random function, randomize function is used to initialize random number generator. If you don't use randomize function then you will get same random numbers each time you run the program.

C programming code using rand

#include <stdio.h>
#include <stdlib.h>
 
int main() {
  int c, n;
 
  printf("Ten random numbers in [1,100]\n");
 
  for (c = 1; c <= 10; c++) {
    n = rand()%100 + 1;
    printf("%d\n", n);
  }
 
  return 0;
}

C programming code using random function(Turbo C compiler only)

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
 
main()
{
   int n, max, num, c;
 
   printf("Enter the number of random numbers you want ");
   scanf("%d",&n);
 
   printf("Enter the maximum value of random number ");
   scanf("%d",&max);
 
   printf("%d random numbers from 0 to %d are :-\n",n,max);
   randomize();
 
   for ( c = 1 ; c <= n ; c++ )
   {
      num = random(max);
      printf("%d\n",num);
 
   }
 
   getch();
   return 0;
}

C Program to add two complex numbers


C program to add two complex numbers: this program calculate the sum of two complex numbers which will be entered by the user and then prints it. User will have to enter the real and imaginary parts of two complex numbers. In our program we will add real parts and imaginary parts of complex numbers and prints the complex number, i is the symbol used for iota. For example if user entered two complex numbers as (1 + 2i) and (4 + 6 i) then output of program will be (5+8i). A structure is used to store complex number.

C programming code

#include <stdio.h>
 
struct complex
{
   int real, img;
};
 
int main()
{
   struct complex a, b, c;
 
   printf("Enter a and b where a + ib is the first complex number.\n");
   printf("a = ");
   scanf("%d", &a.real);
   printf("b = ");
   scanf("%d", &a.img);
   printf("Enter c and d where c + id is the second complex number.\n");
   printf("c = ");
   scanf("%d", &b.real);
   printf("d = ");
   scanf("%d", &b.img);
 
   c.real = a.real + b.real;
   c.img = a.img + b.img;
 
   if ( c.img >= 0 )
      printf("Sum of two complex numbers = %d + %di\n",c.real,c.img);
   else
      printf("Sum of two complex numbers = %d %di\n",c.real,c.img);
 
   return 0;
}
Download add complex numbers program executable.

C Program to print date


This c program prints current system date. To print date we will use getdate function.

C programming code (Works in Turbo C only)

#include <stdio.h>
#include <conio.h>
#include <dos.h>
 
main()
{
   struct date d;
 
   getdate(&d);
 
   printf("Current system date is %d/%d/%d",d.da_day,d.da_mon,d.da_year);
   getch();
   return 0;
}

C Program to get ip address


This c program prints ip (internet protocol) address of your computer, system function is used to execute the command ipconfig which prints ip address, subnet mask and default gateway. The code given below works for Windows xp and Windows 7. If you are using turbo c compiler then execute program from folder, it may not work when you are working in compiler and press Ctrl+F9 to run your program.

C programming code

#include<stdlib.h>
 
int main()
{
   system("C:\\Windows\\System32\\ipconfig");
 
   return 0;
}
Download IP address program.

C Program to shutdown or turn off computer


C Program to shutdown your computer: This program turn off i.e shutdown your computer system. Firstly it will asks you to shutdown your computer if you press 'y' the your computer will shutdown in 30 seconds, system function of "stdlib.h" is used to run an executable file shutdown.exe which is present in C:\WINDOWS\system32 in Windows XP. You can use various options while executing shutdown.exe for example -s option shutdown the computer after 30 seconds, if you wish to shutdown immediately then you can write "shutdown -s -t 0" as an argument to system function. If you wish to restart your computer then you can write "shutdown -r".
If you are using Turbo C Compiler then execute your file from folder. Press F9 to build your executable file from source program. When you run from within the compiler by pressing Ctrl+F9 it may not work.

C programming code for Windows XP

#include <stdio.h>
#include <stdlib.h>
 
main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c",&ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown -s");
 
   return 0;
}

C programming code for Windows 7

#include <stdio.h>
#include <stdlib.h>
 
main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c",&ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown /s");
 
   return 0;
}
To shutdown immediately use "C:\\WINDOWS\\System32\\ shutdown /s /t 0". To restart use /r instead of /s.

C programming code for Ubuntu Linux

#include <stdio.h>
 
int main() {
  system("shutdown -P now");
  return 0;
} 
You need to be logged in as root user for above program to execute otherwise you will get the message shutdown: Need to be rootnow specifies that you want to shutdown immediately. '-P' option specifies you want to power off your machine. You can specify minutes as:
shutdown -P "number of minutes"
For more help or options type at terminal: man shutdown.