Archive for the ‘Files’ Category

Copy File

Posted: May 14, 2010 in Files
Tags: ,

/* Program to copy a file to another */

#include<stdio.h>

main()
{
char source[100],destination[100],c;
FILE *fpr,*fpw;
printf(“\nSource File: “);
gets(source);
printf(“\nDestination: “);
gets(destination);
fpr=fopen(source,”r”); // opening source file in read mode
if(fpr) // checking source file opened or not
{
fpw=fopen(destination,”w”); // opening destination file in write mode
if(fpw)// checking destination file opened or not
{
while(!feof(fpr)) // reading and writing continue until the end of source found
{
fscanf(fpr,”%c”,&c); // reading a character from source
fprintf(fpw,”%c”,c); // wring the character into destination
}
printf(“\nFiles Copied Successfully!!\n”);
}
else
printf(“\nError Opening Destination!\n”);
}
else
printf(“\nError Opening Source!\n”);
}

Advertisements

/* Program to write a string to file */

#include<stdio.h>

main()
{
FILE *fp;
char string[100],filename[30];
printf(“\nEnter a string: “);
gets(string); // reading the string
printf(“\nFilename: “);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
fprintf(fp,”%s”,string); // writing the string to the file
fclose(fp);
}

Read a File

Posted: May 14, 2010 in Files
Tags: ,

/* Program to read a file and print it */

#include<stdio.h>

main()
{
FILE *fp;
char filename[30],c;
printf(“\nEnter the filename: “);
scanf(“%s”,filename);
fp=fopen(filename,”r”); // opening source file in read mode
if(!fp)
printf(“\nError Opening File!!\n”);
else
{
while(!feof(fp))
{
fscanf(fp,”%c”,&c); // reading from file
printf(“%c”,c);
}
fclose(fp);
}
}