Steps of Learning @ Temple of Knowledge

Click here to edit subtitle


prepard by

VIVEKANANDAREDDY P

Assistant Professor,
Department of computer science

The C program is successfully compiled and run on a Linux system. The program output is also shown below.

Create a File & Store Information :

  1. C program to create a file called emp.rec and store information
  2.  * about a person, in terms of his name, age and salary.
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8. FILE *fptr;
  9. char name[20];
  10. int age;
  11. float salary;
  12.  
  13. /* open for writing */
  14. fptr = fopen("emp.rec", "w");
  15.  
  16. if (fptr == NULL)
  17. {
  18. printf("File does not exists \n");
  19. return;
  20. }
  21. printf("Enter the name \n");
  22. scanf("%s", name);
  23. fprintf(fptr, "Name = %s\n", name);
  24. printf("Enter the age\n");
  25. scanf("%d", &age);
  26. fprintf(fptr, "Age = %d\n", age);
  27. printf("Enter the salary\n");
  28. scanf("%f", &salary);
  29. fprintf(fptr, "Salary = %.2f\n", salary);
  30. fclose(fptr);
  31. }

  32. $ cc pgm95.c
    $ a.out
    Enter the name
    raj
    Enter the age
    40
    Enter the salary
    4000000



  1. /*
  2.  * C program to illustrate how a file stored on the disk is read
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. void main()
  8. {
  9.     FILE *fptr;
  10.     char filename[15];
  11.     char ch;
  12.  
  13.     printf("Enter the filename to be opened \n");
  14.     scanf("%s", filename);
  15.     /*  open the file for reading */
  16.     fptr = fopen(filename, "r");
  17.     if (fptr == NULL)
  18.     {
  19.         printf("Cannot open file \n");
  20.         exit(0);
  21.     }
  22.     ch = fgetc(fptr);
  23.     while (ch != EOF)
  24.     {
  25.         printf ("%c", ch);
  26.         ch = fgetc(fptr);
  27.     }
  28.     fclose(fptr);
  29. }




$ cc pgm96.c
$ a.out
Enter the filename to be opened
pgm95.c
/*
 * C program to create a file called emp.rec and store information
 * about a person, in terms of his name, age and salary.
 */
 
#include <stdio.h>
 
void main()
{
    FILE *fptr;
    char name[20];
    int age;
    float salary;
 
    fptr = fopen ("emp.rec", "w"); /* open for writing*/
 
    if (fptr == NULL)
    {
        printf("File does not exists \n");
        return;
    }
    printf("Enter the name \n");
    scanf("%s", name);
    fprintf(fptr, "Name    = %s\n", name);
    printf("Enter the age \n");
    scanf("%d", &age);
    fprintf(fptr, "Age     = %d\n", age);
    printf("Enter the salary \n");
    scanf("%f", &salary);
    fprintf(fptr, "Salary  = %.2f\n", salary);
    fclose(fptr);
}


  1. /*
  2.  * C Program Delete a specific Line from a Text File
  3.  */
  4. #include <stdio.h>
  5.  
  6. int main()
  7. {
  8.     FILE *fileptr1, *fileptr2;
  9.     char filename[40];
  10.     char ch;
  11.     int delete_line, temp = 1;
  12.  
  13.     printf("Enter file name: ");
  14.     scanf("%s", filename);
  15.     //open file in read mode
  16.     fileptr1 = fopen(filename, "r");
  17.     ch = getc(fileptr1);
  18.  `  while (ch != EOF)
  19.     {
  20.         printf("%c", ch);
  21.         ch = getc(fileptr1);
  22.     }
  23.     //rewind
  24.     rewind(fileptr1);
  25.     printf(" \n Enter line number of the line to be deleted:");
  26.     scanf("%d", &delete_line);
  27.     //open new file in write mode
  28.     fileptr2 = fopen("replica.c", "w");
  29.     ch = getc(fileptr1);
  30.     while (ch != EOF)
  31.     {
  32.         ch = getc(fileptr1);
  33.         if (ch == '\n')
  34.             temp++;
  35.             //except the line to be deleted
  36.             if (temp != delete_line)
  37.             {
  38.                 //copy all lines in file replica.c
  39.                 putc(ch, fileptr2);
  40.             }
  41.     }
  42.     fclose(fileptr1);
  43.     fclose(fileptr2);
  44.     remove(filename);
  45.     //rename the file replica.c to original name
  46.     rename("replica.c", filename);
  47.     printf("\n The contents of file after being modified are as follows:\n");
  48.     fileptr1 = fopen(filename, "r");
  49.     ch = getc(fileptr1);
  50.     while (ch != EOF)
  51.     {
  52.         printf("%c", ch);
  53.         ch = getc(fileptr1);
  54.     }
  55.     fclose(fileptr1);
  56.     return 0;
  57. }


$ cc pgm47.c $ a.out Enter file name: pgm1.c /* * C PROGRAM TO CONVERSION FROM Decimal to hexadecimal */   #include<stdio.h> int main() { long int decimalnum, remainder, quotient; int i = 1, j, temp; char hexadecimalnum[100];   printf("Enter any decimal number: "); scanf("%ld", &decimalnum);   quotient = decimalnum;   while (quotient != 0) { temp = quotient % 16; //To convert integer into character if (temp < 10) temp = temp + 48; else temp = temp + 55;   hexadecimalnum[i++] = temp; quotient = quotient / 16; }   printf("Equivalent hexadecimal value of decimal number %d: ", decimalnum); for (j = i - 1; j > 0; j--) printf("%c", hexadecimalnum[j]); return 0; }     Enter line number of the line to be deleted: 10   The contents of file after being modified are as follows: * * C PROGRAM TO CONVERSION FROM Decimal to hexadecimal */   #include<stdio.h> int main() { long int decimalnum, remainder, quotient; int i = 1, j, temp;   printf("Enter any decimal number: "); scanf("%ld", &decimalnum);   quotient = decimalnum;   while (quotient != 0) { temp = quotient % 16; //To convert integer into character if (temp < 10) temp = temp + 48; else temp = temp + 55;   hexadecimalnum[i++] = temp; quotient = quotient / 16; }   printf("Equivalent hexadecimal value of decimal number %d: ", decimalnum); for (j = i - 1; j > 0; j--) printf("%c", hexadecimalnum[j]); return 0; }



  1. /*
  2.  * C Program to Replace a specified Line in a Text File
  3.  */
  4. #include <stdio.h>
  5.  
  6. int main(void)
  7. {
  8.     FILE *fileptr1, *fileptr2;
  9.     char filechar[40];
  10.     char c;
  11.     int delete_line, temp = 1;
  12.  
  13.     printf("Enter file name: ");
  14.     scanf("%s", filechar);
  15.     fileptr1 = fopen(filechar, "r");
  16.     c = getc(fileptr1);
  17.     //print the contents of file .
  18.     while (c != EOF)
  19.     {
  20.         printf("%c", c);
  21.         c = getc(fileptr1);
  22.     }
  23.     printf(" \n Enter line number to be deleted and replaced");
  24.     scanf("%d", &delete_line);
  25.     //take fileptr1 to start point.
  26.     rewind(fileptr1);
  27.     //open replica.c in write mode
  28.     fileptr2 = fopen("replica.c", "w");
  29.     c = getc(fileptr1);
  30.     while (c != EOF)
  31.     {
  32.         if (c == 'n')
  33.         {
  34.             temp++;
  35.         }
  36.         //till the line to be deleted comes,copy the content to other
  37.         if (temp != delete_line)
  38.         {
  39.             putc(c, fileptr2);
  40.         }
  41.         else
  42.         {
  43.             while ((c = getc(fileptr1)) != 'n')
  44.             {
  45.             }
  46.             //read and skip the line ask for new text
  47.             printf("Enter new text");
  48.             //flush the input stream
  49.             fflush(stdin);
  50.             putc('n', fileptr2);
  51.             //put 'n' in new file
  52.             while ((c = getchar()) != 'n')
  53.                 putc(c, fileptr2);
  54.             //take the data from user and place it in new file
  55.             fputs("n", fileptr2);
  56.             temp++;
  57.         }
  58.         //continue this till EOF is encountered
  59.         c = getc(fileptr1);
  60.     }
  61.     fclose(fileptr1);
  62.     fclose(fileptr2);
  63.     remove(filechar);
  64.     rename("replica.c", filechar);
  65.     fileptr1 = fopen(filechar, "r");
  66.     //reads the character from file
  67.     c = getc(fileptr1);
  68.     //until last character of file is encountered
  69.     while (c != EOF)
  70.     {
  71.         printf("%c", c);
  72.         //all characters are printed
  73.         c = getc(fileptr1);
  74.     }
  75.     fclose(fileptr1);
  76.     return 0;
  77. }





$ cc pgm48.c
$ a.out
Enter file name: pgm3.c
/*
 * C Program to Convert Octal to Decimal
 */
 
#include <stdio.h>
#include <math.h>
 
int main()
{
 
    long int octal, decimal = 0;
    int i = 0;
 
    printf("Enter any octal number: ");
    scanf("%ld", &octal);
    while (octal != 0)
    {
        decimal =  decimal +(octal % 10)* pow(8, i++);
        octal = octal / 10;
    }
    printf("Equivalent decimal value: %ld",decimal);
    return 0;
}
 
Enter line number to be deleted and replaced 13 replaced
Enter new text
/*
 * C Program to Convert Octal to Decimal
 */
 
#include <stdio.h>
#include <math.h>
 
int main()
{
 
    long int octal, decimal = 0;
    int i = 0;
 replaced
    printf("Enter any octal number: ");
    scanf("%ld", &octal);
    while (octal != 0)
    {
        decimal =  decimal +(octal % 10)* pow(8, i++);
        octal = octal / 10;
    }
    printf("Equivalent decimal value: %ld",decimal);
    return 0;
}






  1. *
  2.  * C Program to Find the Number of Lines in a Text File
  3.  */
  4. #include <stdio.h>
  5.  
  6. int main()
  7. {
  8.     FILE *fileptr;
  9.     int count_lines = 0;
  10.     char filechar[40], chr;
  11.  
  12.     printf("Enter file name: ");
  13.     scanf("%s", filechar);
  14.     fileptr = fopen(filechar, "r");
  15.    //extract character from file and store in chr
  16.     chr = getc(fileptr);
  17.     while (chr != EOF)
  18.     {
  19.         //Count whenever new line is encountered
  20.         if (chr == 'n')
  21.         {
  22.             count_lines = count_lines + 1;
  23.         }
  24.         //take next character from file.
  25.         chr = getc(fileptr);
  26.     }
  27.     fclose(fileptr); //close file.
  28.     printf("There are %d lines in %s  in a file\n", count_lines, filechar);
  29.     return 0;
  30. }




$ cc pgm49.c
$ a.out
Enter file name: pgm2.c
There are 43 lines in pgm2.c  in a file



  1. /*
  2.  * C Program to Append the Content of File at the end of Another
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. main()
  8. {
  9.     FILE *fsring1, *fsring2, *ftemp;
  10.     char ch, file1[20], file2[20], file3[20];
  11.  
  12.     printf("Enter name of first file ");
  13.     gets(file1);
  14.     printf("Enter name of second file ");
  15.     gets(file2);
  16.     printf("Enter name to store merged file ");
  17.     gets(file3);
  18.     fsring1 = fopen(file1, "r");
  19.     fsring2 = fopen(file2, "r");
  20.     if (fsring1 == NULL || fsring2 == NULL)
  21.     {
  22.         perror("Error has occured");
  23.         printf("Press any key to exit...\n");
  24.         exit(EXIT_FAILURE);
  25.     }
  26.     ftemp = fopen(file3, "w");
  27.     if (ftemp == NULL)
  28.     {
  29.         perror("Error has occures");
  30.         printf("Press any key to exit...\n");
  31.         exit(EXIT_FAILURE);
  32.     }
  33.     while ((ch = fgetc(fsring1)) != EOF)
  34.         fputc(ch, ftemp);
  35.     while ((ch = fgetc(fsring2) ) != EOF)
  36.         fputc(ch, ftemp);
  37.     printf("Two files merged  %s successfully.\n", file3);
  38.     fclose(fsring1);
  39.     fclose(fsring2);
  40.     fclose(ftemp);
  41.     return 0;
  42. }



$ cc pgm47.c
$ a.out
Enter name of first file a.txt
Enter name of second file b.txt
Enter name to store merged file merge.txt
Two files merged merge.txt successfully.









  1. /*
  2.  * C Program that Merges Lines Alternatively from 2 Files & Print Result
  3.  */
  4. #include<stdio.h>
  5. main()
  6. {
  7.     char file1[10], file2[10];
  8.  
  9.     puts("enter the name of file 1");      /*getting the names of file to be concatenated*/
  10.     scanf("%s", file1);
  11.     puts("enter the name of file 2");
  12.     scanf("%s", file2);
  13.     FILE *fptr1, *fptr2, *fptr3;
  14.     fptr1=fopen(file1, "r");             /*opening the files in read only mode*/
  15.     fptr2=fopen(file2, "r");
  16.     fptr3=fopen("merge2.txt", "w+");   /*opening a new file in write,update mode*/
  17.     char str1[200];
  18.     char ch1, ch2;
  19.     int n = 0, w = 0;
  20.     while (((ch1=fgetc(fptr1)) != EOF) && ((ch2 = fgetc(fptr2)) != EOF))
  21.     {
  22.         if (ch1 != EOF)             /*getting lines in alternately from two files*/
  23.         {
  24.             ungetc(ch1, fptr1);
  25.             fgets(str1, 199, fptr1);
  26.             fputs(str1, fptr3);
  27.             if (str1[0] != 'n')
  28.                 n++;      /*counting no. of lines*/
  29.         }
  30.         if (ch2 != EOF)
  31.         {
  32.             ungetc(ch2, fptr2);
  33.             fgets(str1, 199, fptr2);
  34.             fputs(str1, fptr3);
  35.             if (str1[0] != 'n')
  36.                 n++;        /*counting no.of lines*/
  37.         }
  38.     }
  39.     rewind(fptr3);
  40.     while ((ch1 = fgetc(fptr3)) != EOF)       /*countig no.of words*/
  41.     {
  42.         ungetc(ch1, fptr3);
  43.         fscanf(fptr3, "%s", str1);
  44.         if (str1[0] != ' ' || str1[0] != 'n')
  45.             w++;
  46.     }
  47.     fprintf(fptr3, "\n\n number of lines = %d n number of words is = %d\n", n, w - 1);
  48.     /*appendig comments in the concatenated file*/
  49.     fclose(fptr1);
  50.     fclose(fptr2);
  51.     fclose(fptr3);
  52. }



$ cc pgm51.c
$ a.out
enter the name of file 1
c.txt
enter the name of file 2
a.txt
$ vi merge2.txt
All participants will be provided with 1:1 Linux Systems for Lab work. If participants want, they can bring their own laptops with Linux in it. This enable them to do lot of quality assignments even Sanfoundry internship programs are great learning opportunities.
Students with proven credentials only are enrolled for this program and the duration of these programs ranges from 2-6 months full t after the classes are over. If they have Windows, we install virtualization software and Ubuntu Linux virtual appliance on top of windows system.
ime. Student must be passionate about Technology topics. As part of Sanfoundry's biggest open learning initiative, we are looking for interns (student or working professional) in following technolog
 
 number of lines = 4
 number of words is = 114









  1. /*
  2.  * C Program to List Files in Directory
  3.  */
  4. #include <dirent.h>
  5. #include <stdio.h>
  6.  
  7. int main(void)
  8. {
  9.     DIR *d;
  10.     struct dirent *dir;
  11.     d = opendir(".");
  12.     if (d)
  13.     {
  14.         while ((dir = readdir(d)) != NULL)
  15.         {
  16.             printf("%s\n", dir->d_name);
  17.         }
  18.         closedir(d);
  19.     }
  20.     return(0);
  21. }




$ cc pgm59.c
$ a.out
.
..
 b.txt
 pgm2.c
 pgm5.c
1
a.out
a.txt
b.txt
pgm.c
pgm1.c
pgm10.c
pgm11.c
pgm12.c
pgm13.c
pgm14.c
pgm15.c




  1. /* 
  2.  * C Program to Find Sum of Numbers given in Command Line Arguments 
  3.  * Recursively
  4.  */
  5. #include <stdio.h>
  6.  
  7. int count, s = 0;
  8. void sum(int *, int *);
  9.  
  10. void main(int argc, char *argv[])
  11. {
  12.     int i, ar[argc];
  13.     count = argc;
  14.     for (i = 1; i < argc; i++)
  15.     {
  16.         ar[i - 1] = atoi(argv[i]);
  17.     }
  18.     sum(ar, ar + 1);
  19.     printf("%d", s);
  20. }
  21.  
  22. /* computes sum of two numbers recursively */
  23. void sum(int  *a, int  * b)
  24. {
  25.     if (count == 1)
  26.         return;
  27.     s = s + *a + *b;
  28.     count -= 2;
  29.     sum(a + 2, b + 2);
  30. }



$ cc arg4.c
$ a.out 1 2 3 4
sum is 10






  1. /*
  2.  * C Program to Find the Size of File using File Handling Function
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main(int argc, char **argv)
  7. {
  8.     FILE *fp;
  9.     char ch;
  10.     int size = 0;
  11.  
  12.     fp = fopen(argv[1], "r");
  13.     if (fp == NULL)
  14.         printf("\nFile unable to open ");
  15.     else 
  16.         printf("\nFile opened ");
  17.     fseek(fp, 0, 2);    /* file pointer at the end of file */
  18.     size = ftell(fp);   /* take a position of file pointer un size variable */
  19.     printf("The size of given file is : %d\n", size);    
  20.     fclose(fp);
  21. }






vi file10.c
$ cc file10.c
$ a.out myvmlinux
 
File opened The size of given file is : 3791744




  1. /*
  2.  * C Program to Capitalize First Letter of every Word in a File
  3.  */
  4. #include <stdio.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7. int to_initcap_file(FILE *); 
  8.  
  9. void main(int argc, char * argv[])
  10. {
  11.     FILE *fp1;
  12.     char fp[10];
  13.     int p;
  14.  
  15.     fp1 = fopen(argv[1], "r+");
  16.     if (fp1 == NULL)
  17.     {
  18.         printf("cannot open the file ");
  19.         exit(0);
  20.     }
  21.     p = to_initcap_file(fp1);
  22.     if (p == 1)    
  23.     {    
  24.         printf("success");
  25.     }
  26.     else
  27.     {
  28.         printf("failure");
  29.     }
  30.     fclose(fp1);
  31. }
  32.  
  33. /* capitalizes first letter of every word */
  34. int to_initcap_file(FILE *fp)
  35. {
  36.     char c;
  37.  
  38.     c = fgetc(fp);
  39.     if (c >= 'a' && c <= 'z')
  40.     {
  41.         fseek(fp, -1L, 1);
  42.         fputc(c - 32, fp);
  43.     }
  44.     while(c != EOF)    
  45.     {
  46.         if (c == ' ' || c == '\n')
  47.         {
  48.             c = fgetc(fp);
  49.             if (c >= 'a' && c <= 'z')
  50.             {
  51.                 fseek(fp, -1L, 1);
  52.                 fputc(c - 32, fp);
  53.             }
  54.         }
  55.         else
  56.         {
  57.             c = fgetc(fp);
  58.         }
  59.     }
  60.     return 1;
  61. }





$ cc file5.c
$ a.out sample
success
$ cat sample
Wipro Technologies
File Copy Function
Successfully Read















  1. /*
  2.  * C Program to Print Environment variables
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main(int argc, char *argv[], char * envp[])
  7. {
  8.     int i;
  9.  
  10.     for (i = 0; envp[i] != NULL; i++)
  11.     {    
  12.         printf("\n%s", envp[i]);
  13.     }
  14. }


$ cc arg7.c
$ a.out
 
HOSTNAME=localhost.localdomain
SELINUX_ROLE_REQUESTED=
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
SSH_CLIENT=192.168.7.43 49162 22
SELINUX_USE_CURRENT_RANGE=
QTDIR=/usr/lib64/qt-3.3
QTINC=/usr/lib64/qt-3.3/include
SSH_TTY=/dev/pts/8
USER=harika
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.tbz=01;31:*.tbz2=01;31:*.bz=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/harika/bin:.
MAIL=/var/spool/mail/harika
PWD=/home/harika
KDE_IS_PRELINKED=1
LANG=en_US.UTF-8
KDEDIRS=/usr
SELINUX_LEVEL_REQUESTED=
HISTCONTROL=ignoredups
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
HOME=/home/harika
SHLVL=2
LOGNAME=harika
CVS_RSH=ssh
QTLIB=/usr/lib64/qt-3.3/lib
SSH_CONNECTION=192.168.7.43 49162 192.168.7.140 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
_=./a.out
OLDPWD=/home





  1. /*
  2.  * C Program to Copy a File into Another File
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main(int argc,char **argv)
  7. {
  8.     FILE *fp1, *fp2;
  9.     char ch;
  10.     int pos;
  11.  
  12.     if ((fp1 = fopen(argv[1],"r")) == NULL)    
  13.     {    
  14.         printf("\nFile cannot be opened");
  15.         return;
  16.     }
  17.     else     
  18.     {
  19.         printf("\nFile opened for copy...\n ");    
  20.     }
  21.     fp2 = fopen(argv[2], "w");  
  22.     fseek(fp1, 0L, SEEK_END); // file pointer at end of file
  23.     pos = ftell(fp1);
  24.     fseek(fp1, 0L, SEEK_SET); // file pointer set at start
  25.     while (pos--)
  26.     {
  27.         ch = fgetc(fp1);  // copying file character by character
  28.         fputc(ch, fp2);
  29.     }    
  30.     fcloseall();    
  31. }






$ cc file1.c
$ a.out /tmp/vmlinux mylinux
 
File opened for copy...
 
$cmp /tmp/vmlinux mylinux
 
$ ls -l mylinux
-rw-rw-r--. 1 adi adi 3791744 Jul 27 19:57 mylinux



  1. /*
  2.  * C Program to Create Employee Record and Update it
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #define size 200
  8.  
  9. struct emp
  10. {
  11.     int id;
  12.     char *name;
  13. }*emp1, *emp3;
  14.  
  15. void display();
  16. void create();
  17. void update();
  18.  
  19. FILE *fp, *fp1;
  20. int count = 0;
  21.  
  22. void main(int argc, char **argv)
  23. {
  24.     int i, n, ch;
  25.  
  26.     printf("1] Create a Record\n");
  27.     printf("2] Display Records\n");
  28.     printf("3] Update Records\n");
  29.     printf("4] Exit");
  30.     while (1)
  31.     {
  32.         printf("\nEnter your choice : ");
  33.         scanf("%d", &ch);
  34.         switch (ch)
  35.         {
  36.         case 1:    
  37.             fp = fopen(argv[1], "a");
  38.             create();
  39.             break;
  40.         case 2:    
  41.             fp1 = fopen(argv[1],"rb");
  42.             display();
  43.             break;
  44.         case 3:    
  45.             fp1 = fopen(argv[1], "r+");
  46.             update();
  47.             break;
  48.         case 4: 
  49.             exit(0);
  50.         }
  51.     }
  52. }
  53.  
  54. /* To create an employee record */
  55. void create()
  56. {
  57.     int i;
  58.     char *p;
  59.  
  60.     emp1 = (struct emp *)malloc(sizeof(struct emp));
  61.     emp1->name = (char *)malloc((size)*(sizeof(char)));
  62.     printf("Enter name of employee : ");
  63.     scanf(" %[^\n]s", emp1->name);
  64.     printf("Enter emp id : ");
  65.     scanf(" %d", &emp1->id);
  66.     fwrite(&emp1->id, sizeof(emp1->id), 1, fp);
  67.     fwrite(emp1->name, size, 1, fp);
  68.     count++;   // count to number of entries of records
  69.     fclose(fp);
  70. }
  71.  
  72. /* Display the records in the file */
  73. void display()
  74. {    
  75.     emp3=(struct emp *)malloc(1*sizeof(struct emp));    
  76.     emp3->name=(char *)malloc(size*sizeof(char));
  77.     int i = 1;
  78.  
  79.     if (fp1 == NULL)    
  80.         printf("\nFile not opened for reading");
  81.     while (i <= count)
  82.     {
  83.         fread(&emp3->id, sizeof(emp3->id), 1, fp1);
  84.         fread(emp3->name, size, 1, fp1);
  85.         printf("\n%d %s",emp3->id,emp3->name);
  86.         i++;
  87.     }
  88.     fclose(fp1);
  89.     free(emp3->name);
  90.     free(emp3); 
  91. }
  92.  
  93. void update()
  94. {
  95.     int id, flag = 0, i = 1;
  96.     char s[size];
  97.  
  98.     if (fp1 == NULL)
  99.     {
  100.         printf("File cant be opened");
  101.         return;
  102.     }
  103.     printf("Enter employee id to update : ");
  104.     scanf("%d", &id);
  105.     emp3 = (struct emp *)malloc(1*sizeof(struct emp));
  106.         emp3->name=(char *)malloc(size*sizeof(char));
  107.     while(i<=count)
  108.     {    
  109.         fread(&emp3->id, sizeof(emp3->id), 1, fp1);
  110.         fread(emp3->name,size,1,fp1);
  111.         if (id == emp3->id)
  112.         {
  113.             printf("Enter new name of emplyee to update : ");    
  114.             scanf(" %[^\n]s", s);
  115.             fseek(fp1, -204L, SEEK_CUR);
  116.             fwrite(&emp3->id, sizeof(emp3->id), 1, fp1);
  117.             fwrite(s, size, 1, fp1);
  118.             flag = 1;
  119.             break;
  120.         }
  121.         i++;
  122.     }
  123.     if (flag != 1)
  124.     {
  125.         printf("No employee record found");
  126.         flag = 0;
  127.     }
  128.     fclose(fp1);
  129.     free(emp3->name);        /* to free allocated memory */
  130.     free(emp3);
  131. }




$ a.out emprec1
 
1] Create a Record
2] Display Records
3] Update Records
4] Exit
Enter your choice : 1
Enter name of employee : aaa
Enter emp id : 100 
 
Enter your choice : 1
Enter name of employee : bbb
Enter emp id : 200
 
Enter your choice : 1
Enter name of employee : ccc
Enter emp id : 300
 
Enter your choice : 1
Enter name of employee : ddd
Enter emp id : 400
 
Enter your choice : 1
Enter name of employee : eee
Enter emp id : 500 
 
Enter your choice : 2
 
100 aaa
200 bbb
300 ccc
400 ddd
500 eee
Enter your choice : 3
Enter employee id to update : 300
Enter new name of emplyee to update : cdefgh
 
Enter your choice : 2
 
100 aaa
200 bbb
300 cdefgh
400 ddd
500 eee
Enter your choice : 4










  1. /*
  2.  * C Program to Compare two Binary Files, Printing the First Byte 
  3.  * Position where they Differ
  4.  */
  5. #include <stdio.h>
  6.  
  7. void compare_two_binary_files(FILE *,FILE *);
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11.     FILE *fp1, *fp2;
  12.  
  13.     if (argc < 3)
  14.     {
  15.         printf("\nInsufficient Arguments: \n");
  16.         printf("\nHelp:./executable <filename1> <filename2>\n");
  17.         return;
  18.     }
  19.     else
  20.     {
  21.         fp1 = fopen(argv[1],  "r");
  22.         if (fp1 == NULL)
  23.         {
  24.             printf("\nError in opening file %s", argv[1]);
  25.             return;
  26.         }
  27.  
  28.         fp2 = fopen(argv[2], "r");
  29.  
  30.         if (fp2 == NULL)
  31.         {
  32.             printf("\nError in opening file %s", argv[2]);
  33.             return;
  34.         }
  35.  
  36.         if ((fp1 != NULL) && (fp2 != NULL))
  37.         {
  38.             compare_two_binary_files(fp1, fp2);
  39.         }
  40.     }
  41. }
  42.  
  43. /*
  44.  * compare two binary files character by character
  45.  */
  46. void compare_two_binary_files(FILE *fp1, FILE *fp2)
  47. {
  48.     char ch1, ch2;
  49.     int flag = 0;
  50.  
  51.     while (((ch1 = fgetc(fp1)) != EOF) &&((ch2 = fgetc(fp2)) != EOF))
  52.     {
  53.         /*
  54.           * character by character comparision
  55.           * if equal then continue by comparing till the end of files
  56.           */
  57.         if (ch1 == ch2)
  58.         {
  59.             flag = 1;
  60.             continue;
  61.         }
  62.         /*
  63.           * If not equal then returns the byte position
  64.           */
  65.         else
  66.         {
  67.             fseek(fp1, -1, SEEK_CUR);        
  68.             flag = 0;
  69.             break;
  70.         }
  71.     }
  72.  
  73.     if (flag == 0)
  74.     {
  75.         printf("Two files are not equal :  byte poistion at which two files differ is %d\n", ftell(fp1)+1);
  76.     }
  77.     else
  78.     {
  79.         printf("Two files are Equal\n ", ftell(fp1)+1);
  80.     }
  81. }






$ gcc file15.c
$ a.out /bin/chgrp /bin/chown
Two files are not equal :  byte poistion at which two files differ is 25
 
/*
 * Verify using cmp command
 */
$ cmp /bin/chgrp /bin/chown
/bin/chgrp /bin/chown differ: byte 25,  line 1
 
$ a.out a.out a.out
Two files are Equal
/*
 * Verify using cmp command
 */
$ cmp a.out a.out






  1. /*
  2.  * C Program to Convert the Content of File to UpperCase
  3.  */
  4. #include <stdio.h>
  5.  
  6. int to_upper_file(FILE *);
  7.  
  8. int main(int argc,char *argv[])
  9. {
  10.     FILE *fp;
  11.     int status;
  12.  
  13.     if (argc == 1)
  14.     {
  15.         printf("Insufficient Arguments:");
  16.         printf("No File name is provided at command line");
  17.         return;
  18.     }
  19.     if (argc > 1)
  20.     {
  21.         fp = fopen(argv[1],"r+");
  22.         status = to_upper_file(fp);
  23.  
  24.         /* 
  25.           *If the status returned is 0 then the coversion of file content was completed successfully
  26.          */
  27.  
  28.         if (status == 0)
  29.         {
  30.             printf("\n The content of \"%s\" file was successfully converted to upper case\n",argv[1]);
  31.             return;
  32.         }
  33.         /*
  34.           * If the status returnes is -1 then the conversion of file content was not done
  35.           */
  36.         if (status == -1)
  37.         {
  38.             printf("\n Failed to convert");
  39.             return;
  40.         } 
  41.    }
  42. }
  43.  
  44. /*
  45.  * convert the file content to uppercase
  46.  */
  47. int to_upper_file(FILE *fp)
  48. {
  49.     char ch;
  50.  
  51.     if (fp == NULL)
  52.     {
  53.         perror("Unable to open file");
  54.         return -1;
  55.     }
  56.     else
  57.     {
  58.         /*
  59.           * Read the file content and convert to uppercase
  60.           */
  61.         while (ch != EOF)
  62.         {
  63.             ch = fgetc(fp);
  64.             if ((ch >= 'a') && (ch <= 'z'))
  65.             {
  66.                 ch = ch - 32;
  67.                 fseek(fp,-1,SEEK_CUR);
  68.                 fputc(ch,fp);
  69.             }    
  70.         }
  71.         return 0;
  72.     }
  73. }






/* Input file : mydata
$ cat mydata
This is Manish
I had worked in Wipro and Cisco
*/
 
$ gcc file3.c
$ a.out mydata
The content of "mydata" file was successfully converted to upper case
 
/* "mydata" after conversion
$ cat mydata
THIS IS MANISH
I HAD WORKED IN WIPRO AND CISCO
*/





  1. /*
  2.  * C Program to replace first letter of every word with caps
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. void main(int argc, char *argv[])
  8. {
  9.     FILE *fp1;
  10.     int return_val;
  11.  
  12.     if ((fp1 = fopen(argv[1],"r+")) =  = NULL)
  13.     {
  14.         printf("file cant be opened");
  15.         exit(0);
  16.     }
  17.     return_val = init_cap_file(fp1);
  18.     if (return_val == 1)
  19.     {
  20.         printf("\nsuccess");
  21.     }
  22.     else
  23.     {
  24.         printf("\n failure");
  25.     }
  26. }
  27.  
  28. int init_cap_file(FILE *fp1)
  29. {
  30.     char ch;
  31.  
  32.     ch = fgetc(fp1);
  33.     if (ch >= 97 && ch <= 122)
  34.     {
  35.         fseek(fp1, -1L, 1);
  36.         fputc(ch - 32, fp1);
  37.     }
  38.     while (ch != EOF)
  39.     {
  40.         if (ch = = ' '|| ch == '\n')
  41.         {
  42.             ch = fgetc(fp1);
  43.             if (ch >= 97 && ch <= 122)
  44.             {
  45.                 fseek(fp1, -1L, 1);
  46.                 fputc(ch - 32, fp1);
  47.             }
  48.         }
  49.         else
  50.             ch = fgetc(fp1);
  51.     }
  52.     return 1;
  53. }



$ vi file5test $ cat file5test chandana ravella chanikya ravella sree lakshmi ravella sree ramulu ravella $ cc file5.c $ a.out file5test   success$ cat file5test Chandana Ravella Chanikya Ravella Sree Lakshmi Ravella Sree Ramulu Ravella




  1.         }
  2.     }
  3.     fseek(fp1, 0, 0);
  4.     while ((ch = fgetc(fp1))! = EOF)
  5.     {
  6.         if (ch  ==  '/')
  7.         {
  8.             if ((ch = fgetc(fp1))  ==  '/')
  9.             {
  10.                 n_o_c_l++;
  11.             }
  12.         }
  13.     }
  14.     printf("Total no of lines: %d\n", line_count);
  15.     printf("Total no of comment line: %d\n", n_o_c_l);
  16.     printf("Total no of blank lines: %d\n", n_o_b_l);
  17.     printf("Total no of non blank lines: %d\n", line_count-n_o_b_l);
  18.     printf("Total no of lines end with semicolon: %d\n", n_e_c);
  19. }





$ cc file8.c
$ a.out stack_ll.c
Total no of lines: 204
Total no of comment line: 19
Total no of blank lines: 11
Total no of non blank lines: 193
Total no of lines end with semicolon: 66




  1. /* 
  2.  * C Program to Reverse the Contents of a File and Print it
  3.  */
  4. #include <stdio.h>
  5. #include <errno.h>
  6.  
  7. long count_characters(FILE *);
  8.  
  9. void main(int argc, char * argv[])
  10. {
  11.     int i;
  12.     long cnt;
  13.     char ch, ch1;
  14.     FILE *fp1, *fp2;
  15.  
  16.     if (fp1 = fopen(argv[1], "r"))    
  17.     {
  18.         printf("The FILE has been opened...\n");
  19.         fp2 = fopen(argv[2], "w");
  20.         cnt = count_characters(fp1); // to count the total number of characters inside the source file
  21.         fseek(fp1, -1L, 2);     // makes the pointer fp1 to point at the last character of the file
  22.         printf("Number of characters to be copied %d\n", ftell(fp1));
  23.  
  24.         while (cnt)
  25.         {
  26.             ch = fgetc(fp1);
  27.             fputc(ch, fp2);
  28.             fseek(fp1, -2L, 1);     // shifts the pointer to the previous character
  29.             cnt--;
  30.         }
  31.         printf("\n**File copied successfully in reverse order**\n");
  32.     }
  33.     else
  34.     {
  35.         perror("Error occured\n");
  36.     }
  37.     fclose(fp1);
  38.     fclose(fp2);
  39. }
  40. // count the total number of characters in the file that *f points to
  41. long count_characters(FILE *f) 
  42. {
  43.     fseek(f, -1L, 2);
  44.     long last_pos = ftell(f); // returns the position of the last element of the file
  45.     last_pos++;
  46.     return last_pos;
  47. }





$ gcc file12.c
$ cat test2
The function STRERROR returns a pointer to an ERROR MSG STRING whose contents are implementation defined.
THE STRING is not MODIFIABLE and maybe overwritten by a SUBSEQUENT Call to the STRERROR function.
$ a.out test2 test_new
The FILE has been opened..
Number of characters to be copied 203
 
**File copied successfully in reverse order**
$ cat test_new
 
.noitcnuf RORRERTS eht ot llaC TNEUQESBUS a yb nettirwrevo ebyam dna ELBAIFIDOM ton si GNIRTS EHT
.denifed noitatnemelpmi era stnetnoc esohw GNIRTS GSM RORRE na ot retniop a snruter RORRERTS noitcnuf ehT
$ ./a.out test_new test_new_2
The FILE has been opened..
Number of characters to be copied 203
 
**File copied successfully in reverse order**
$ cat test_new_2
The function STRERROR returns a pointer to an ERROR MSG STRING whose contents are implementation defined.
THE STRING is not MODIFIABLE and maybe overwritten by a SUBSEQUENT Call to the STRERROR function.
$ cmp test test_new_2