FILE OPERATIONS USING UNIX PROGRAMMING
#include
#include
#include
#include
#include
main()
{
int fd,ch,n,len,p;
char name[20],str[50],buf[40];
do
{
printf("Menu\n");
printf("1.Create a file\n");
printf("2.Open a file\n");
printf("3.Writing to a file\n");
printf("4.Reading from a file\n");
printf("5.Exit\n");
printf("Enter the choice[1-4]:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the filename:\n");
getchar();
gets(name);
fd=creat(name,S_IRWXU);
printf("File Created\n");
close(fd);
break;
case 2:
printf("Enter the filename to open:\n");
getchar();
gets(name);
fd=open(name,O_RDWR);
printf("%d",fd);
if(fd!=3)
{
fd=open(name,O_CREAT O_RDWR);
printf("File is created\n");
}
else
printf("File Already Exist\n");
close(fd);
break;
case 3:
printf("Enter the filename to Write:\n");
getchar();
gets(name);
fd=open(name, O_RDWR);
printf("X=%d",fd);
if (fd==3)
{
printf("File Already Exist\n");
printf("Are you want to Append or overwrite:\n");
printf("0-Append\n");
printf("1-Overwrite\n");
printf("Enter your Choice[1-0]:");
scanf("%d",&ch);
if(ch==0)
lseek(fd,0,SEEK_END);
else
lseek(fd,0,SEEK_SET);
}
else
{
fd=open(name,O_CREAT O_RDWR,S_IRWXU);
printf("New File is created\n");
}
printf("Enter the String to Write\n");
scanf("%s",buf);
len=strlen(buf);
write(fd,buf,len);
close(fd);
break;
case 4:
printf("Enter the filename to read the content:\n");
getchar();
gets(name);
fd=open(name,O_RDWR);
if(fd==3)
{
printf("already exist!\n");
printf("From where you want to read :\n 0-Starting position \n (1-n)-other postion :\n");
scanf("%d",&p);
lseek(fd,p,SEEK_SET);
n=read(fd,buf,10);
buf[n]='\0';
printf("The content of the file is...%s\n",buf);
}
else
{
fd=open(name,O_CREAT O_RDWR,S_IRWXU);
printf("Newly Created No data to Read!");
}
close(fd);
break;
}
}
while(ch<=4);
}