Thursday, October 15, 2009

C Program to read and write into a file...

// Write to file and read from file

#include 
#include 
#include 
#include 
#include 
#include 
#define PATH "/* Give the path where u want to read or write the file*/ "


void writefile(char *path)
{
 char pathname[256], name[32], ch;
 int handle;

 strcpy(pathname,path);

 printf("\nEnter file name : ");
 scanf("%s",name);
 
 strcat(pathname,name);
 
 handle = open(pathname, O_WRONLY|O_CREAT|O_TRUNC, 0666);

 if(handle == -1)
 {
  perror("file open");
 }
 else
 {
  printf("\nInsert data in file : ");
  while((ch=getchar()) != '^')
  {
   write(handle, &ch, sizeof(char));
  }
 }

 close(handle);
}


void readfile(char *path)
{
 char pathname[256], name[32], ch;
 int handle;

 strcpy(pathname, path);

 printf("\nEnter file name : ");
 scanf("%s",name);
 strcat(pathname,name);

 handle = open(pathname, O_RDONLY);

 if(handle == -1)
 {
  perror("file open");
 }
 else 
 {
  while(read(handle, &ch, sizeof(char))!= 0)
   putchar(ch);
 }

 close(handle);
}



int main()
{
 int ch;

 do
 {
  printf("1.WRITE TO FILE\n2.READ FROM FILE\n3.EXIT\n");
  printf("\nEnter choice : ");
  scanf("%d",&ch);

  switch(ch)
  {
   case 1: writefile(PATH);
     break;
   case 2: readfile(PATH);
     break;
  }
 }while(ch != 3);
 
 return 0;
}

No comments:

Post a Comment