Wednesday, October 30, 2013

To Study the File-Handling

/*
To Study the File-Handling
*/


#include<stdio.h>
#include<fcntl.h>
#include<error.h>
#include<string.h>
#include<sys/wait.h>

int fd;
char name1[100];
void createfile(char *name)
{
printf("\n Enter name of file \n");
scanf("%s",name);
fd=open(name,O_CREAT|O_EXCL,0760);
if(fd==-1)
{
perror("\n ERROR!!!\n");
exit(1);
}

else
{
printf("\nfile created");
close(fd);
}
}


void copy()
{
char ch;
int n;
char name1[100], name2[100];
int fd1, fd2;
printf("\n Enter name of file to copy");
scanf("%s",name1);
fd1=open(name1,O_RDWR|O_APPEND,0760);
printf("\nEnter name of file to be copied into");
scanf("%s",name2);
fd2=open(name2,O_CREAT|O_EXCL|O_RDWR|O_APPEND,0761);
if(fd1==-1)
{
perror("\n ERROR!!!\n");
exit(1);
}
if(fd2==-1)
{
perror("\n ERROR!!!\n");
exit(1);
}


while(read(fd1,&ch,1)>0);
{
write(fd2,&ch,1);
}


printf("\n copied");
close(fd1);
close(fd2);
}
void writeandread()
{
char ch;
int n;
char name2[100], buff[100], buff1[100];
int fd1;
printf("\n Enter name of file to write");
scanf("%s",name1);
fd1=open(name1,O_RDWR|O_APPEND,0760);
/*printf("\nEnter name of file");
scanf("%s",name2);
fd2=open(name2,O_CREAT|O_EXCL|O_RDWR|O_APPEND,0761);
*/
if(fd1==-1)
{
perror("\n ERROR!!!\n");
exit(1);
}

else
{
printf("\nEnter to write");
scanf("%s",buff);
write(fd1,buff,strlen(buff));
printf("\nwrite succesfull");
lseek(fd1,0,SEEK_SET);
read(fd1,buff1,strlen(buff));
printf("\nfile contains: %s\n",buff1);
}
printf("\nexiting");
close(fd1);

}

int main()

{
char name[100];
createfile(name);
        writeandread();
copy();
return 0;
}

/*
OUTPUT:
bash-3.00$ cc file.c
bash-3.00$ ./a.out

Enter name of file a1

file created
 Enter name of file to write a1

Enter to write hi

write succesfull
file contains: hij

exiting
 Enter name of file to copy a1

Enter name of file to be copied into a2

 copiedbash-3.00$ ./a.out
*/

No comments:

Post a Comment