Wednesday, November 11, 2009

Chap12[C]f Merge alternate lines from two files

Write a program that merges lines alternately from two files and writes the results to new file. If one file has less number of lines than the other, the remaining lines from the larger file should be simply copied into the target file.

#include "stdio.h"
void main()
{
FILE *fp,*ft,*fs;
char ch;
int f1=1,f2=1,counter=1;

fp=fopen("c:\\ctxt\\first.txt","r");
ft=fopen("c:\\ctxt\\second.txt","r");
fs=fopen("c:\\ctxt\\combine.txt","w");

while(1)
{
if(counter==1||f2==0)
{
ch=fgetc(fp);
if(ch==EOF)
f1=0;
if(ch=='\n'||ch==46)
counter=2;
if(f1!=0)
fputc(ch,fs);
}

if(counter==2||f1==0)
{
ch=fgetc(ft);
if(ch==EOF)
f2=0;

if(ch=='\n'||ch==46)
counter=1;
if(f2!=0)
fputc(ch,fs);

if(f1==0&&f2==0)
break;
}
}

fclose(fp);
fclose(ft);
fclose(fs);
}

Chap12[C]e Lowercase to uppercase in file

Write a program to copy one file to another. While doing so replace all lowercase characters to their equivalent uppercase characters.

#include "stdio.h"

void main()
{
FILE *fp,*ft;
char ch;

fp=fopen("c:\\ctxt\\txt1.txt","r");
ft=fopen("c:\\ctxt\\txt2.txt","w");

if(fp==NULL)
{
puts("Cannot open file");
exit();
}

if(ft==NULL)
{
puts("Cannot open file");
exit();
}

while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
if(ch>=97&&ch<=122)
ch-=32;
fputc(ch,ft);
}

fclose(fp);
fclose(ft);
}

Chap12[C]c Add contents of file on another

Write a program to add the contents of one file at the end of another.

#include "stdio.h"

void main()
{
FILE *fp,*ft;
char ch,ch2;
int f=0;
fp=fopen("c:\\ctxt\\12cc1.txt","a");
ft=fopen("c:\\ctxt\\12cc2.txt","r");

fprintf(fp,"\n");
while(1)
{

ch=fgetc(ft);
if(ch==EOF)
break;

fputc(ch,fp);


}
fclose(fp);
fclose(ft);
}

Chap12[C]a Read file and display line numbers

Write a program to read a file and display contents with its line numbers.

#include "stdio.h"
void main()
{
FILE *fp;
char ch;
int c=1;
fp=fopen("c:\\ctxt\\12ca.txt","r");
if(fp==NULL)
{
puts("File cannot be opened");
exit();
}
clrscr();
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
if(ch=='\n')
c++;
printf("%c",ch);
}
printf("\nThe number of lines is %d",c);
}