Featured Post

Sunday, January 29, 2017

File handling in C

main()
{
   int a,b,c;
  clrscr();
  printf("enter any any two values");
  scanf("%d%d",&a,&b);
  c=a+b;
  printf("addition of %d and %d is %d",a,b,c);
 getch();
}

output: enter any two numbers
5
3
addition of 5 and 3 is 8
lets execute again!
enter any two values
13
12
addition of 13 and 12 is 25
every thing is ok ! but what about previous input and output values?


so this is the problem while executing c program using  standard input output devices.

So if want to store input data and output data permanently then we have to go for files.

So lets move out attention to files.
So if we want to store input data and output data permanently then we have to go for files.


A file is a collection of data stored on a disk.
Simply to say file handling deals with creation of text documents, editing text, and deletion of text documents. 
For example consider creation of notepad document, copy of one notepad document to another document etc
So to do operations on file we have to use some library functions
fopen()-->to open a text file

getc()-->to read a single character from a file where the pointer is pointing

putc()-->to put a single character in a file where the pointer is pointing

getw()-->to read a single integer value from a file where the pointer is pointing

putw()---> to put a single integer in a file where the pointer is pointing

fprintf()-->to display different types of data on to the screen at a time

fscnaf()-->to read different types of data from the key board in a single function

fclose()--->to close the open file

Hope you  all understand what am saying?

lets go in depth

fopen():
  
   fopen() function is used to open an existing file or to create the new file if not exist

   Note the every file program in c begins with:

   FILE *fp;
  where fp is a pointer pointing to the some location of the file.

 now we write fopen() syntax

fp=fopen("file name","mode");

example:
 main()
{
 FILE *fp;
fp=fopen("hello.txt","w");/*opening file */
-----
-------
------
fclose(fp);/*closing file pointer*/
}

seeing above example one more thing discuss
mode:

   mode specifies the type of operation to be done on file
  r--->to open a file in read mode.(make sure the opened file must exist other wise error returns)


No comments:

Post a Comment