fopen(): This function is used to open an existing file or to create a new file
FILE *fp;
fp=fopen(filename, mode);
mode: mode specifies the type of operation to be done on file
r: stands for read mode
w: stands for write mode
a: stands for append mode
getc(): this function is used to read one character at a time from the file opend in read mode.
putc(): this function is used to write one character at a time to a file opend in write mode
fclose(): this function is used to close the opend file
getw():this function is used to read one integer at a time from the file opend in read mode.
putw(): this function is used to write one integer at a time to a file opend in write mode
NOTE: Every file in c ends with EOF (stands for end of file an integer value).
/* C program to create a file and giving input from the keyboard */
main()
{
FILE *fp;
char c;
fp=fopen("sample.txt","w"); /* sample.txt is a new file opend in write mode */
if(fp==NULL)
{
printf("\n file cannot be created ");
exit(1);
}
printf("\n enter your data on to the file");
while((c=getchar())!='$') /* after entering all the data press $(assumed end of the data) */
{
putc(c,fp); /* placing data on to the file one character a time */
}
printf("\n file successfully created");
}
output:
enter your data on to the file
hi raj how are you?$
file successfully created
note: there is no specified end when reading from the keyboard so assuming $ as end of input data or you can assume any other symbol as end of keyboard data
/* C program to display file contents on to the screen*/
main()
{
FILE *fp;
char c;
fp=fopen("sample.txt","r"); /* sample.txt is opend in read mode */
if(fp==NULL)
{
printf("\n file does not exist");
exit(1);
}
while((c=getc(fp))!=EOF) /* EOF stands for end of the file */
{
printf("%c",c); /* placing data on to the screen*/
}
}
OUTPUT:
hi raj how are you?
C program to copy one file to another file
C program to create a file and display file contents on to the screen , file handling in c, random access to a file, random handling in file, random file handling in c, random access to a file in C, getc(), putc(), fopen(), fclose(),getw(),putw(), c program to display file contents on to the screen. different typed of modes in files. differentiate between r and r+ mode, w and w+ mode , a and a+ mode.EOF, end of the file.
No comments:
Post a Comment