Search This Blog

Thursday, 16 October 2014

Advanced Programs in C!

0 comments

Solved Programs in C!

Program 1 :

Write a program to copy contents of one file to another file.  Also find the number of characters, lines and words in the above file.

#include <stdio.h>
void main()
{
    int cc=0, wc=1, lc=1;
    char c;

    FILE *fin;
    FILE *fout;
    fout = fopen("File1.txt","w");

    printf("Enter few lines of Text with # as the last character \n");
    c = getchar();
    while(c != '#')
    {
        cc++;
        putc(c, fout);
        if (c == ' '||c=='\n')
            wc++;
        if (c== '\n')
            lc++;
        c = getchar();
    }
    fclose(fout);

    printf("File created with the name File1.txt\n");
    printf("# of Characters in the file is : %d\n",cc);
    printf("# of Words in the file is : %d\n",wc);
    printf("# of Lines in the file is : %d\n",lc);

    fin = fopen("File1.txt", "r");
    fout = fopen("File2.txt","w");

    while (feof(fin) == 0)
    {
        c = getc(fin);
        putc(c, fout);
    }
    printf("File copy from File1.txt to File2.txt is done Successfully!");
    fclose(fin);
    fclose(fout);
}

Program 2 :

Write a program to read a string S1 from the terminal.  Again read a string S2 from the terminal and check the given string S2 in the string S1.  If it does, remove S2 from the string S1 and print the updated string S1.  (For example S1= Concatenate and S2 = cat, then the final result should be "Conenate"

#include <stdio.h>
#include <string.h>
void main()
{
    int l1=0,l2=0,i,j,k;

    char str1[30], str2[30];
    printf("Enter the String1 :");
    gets(str1);

    printf("Enter the String2 :");
    gets(str2);

    l1 = strlen(str1);
    l2 = strlen(str2);

    if(l2>l1)
        printf("String2 does not exist in String1");
    else
    {
        for(i=0; i<l1; i++)
        {
            for(j=0,k=i; j<l2; j++,k++)
            {
                if(str1[k] == str2[j])
                    continue;
                else
                    break;
            }
            if(j==l2)
            {
                printf("The String2 exists in String1\n");
                break;
            }
        }

        if(j==l2)
        {
            printf("String1 after removing String2 from it : ");
            for(i=0; i<k-j; i++)
                putchar(str1[i]);
            for(i=k; i<l1; i++)
                putchar(str1[i]);
        }
        printf("\n");
    }   
}

Leave a Reply