Function | description |
---|---|
fopen() | Used to create a new file or open a existing file. |
fclose() | Used to close a file. |
fscanf() | Used to read a dataset from a file. |
fprintf() | Used to write data to a file. |
getc() | Used to read characters from files. |
putc() | Used to write a character to a file. |
getw() | Used to read an integer from a file. |
putw() | Used to write an integer to a file. |
rewind() | Used to set the position to the beginning point. |
ftell() | Used to give current position in the file. |
fseek() | Used to set the position to required point. |
fopen()
function. filename
is the name of the file to be opened.
mode
in the syntax which denotes the purpose of creating a file.
*fp
refers to the opened(or created) file. Mode | Description |
---|---|
r | Represents open a file for read |
w | Represents open empty file for writing |
a | Represents open a file to append |
r+ | Represents open a binary file for read and write |
w+ | Represents open a binary file for write and read |
r+ | Represents open a binary file for append and read |
exit()
function in above program is similar to the return function the C main section. getc()
and putc()
are two simple functions to read and write individual characters to a file.
When the user inputs the data, data is written and stored in the file. This can be done by using C File I/O function, fprintf()
function. f in the starting represents the file argument pointed to file structure.
[c]
#include<stdio.h>
int main()
{
int a;
FILE *fp;
fp=fopen("C:\\splessons.txt");
if(fp==NULL)
{
printf("no file exists");
exit(1);
}
printf"Enter a:");
scanf("%d",&a);
fprintf(fp,"%d",a);
fclose(fp);
return 0;
}[/c]
To read the data from a file fscanf()
function is used.
[c]
#include<stdio.h>
int main()
{
int a;
FILE *fp;
if ((fp=fopen("C:\\aplessons.txt")==NULL)
{
printf("Cannot open the file");
exit(1);
}
fscanf(fp,"%d",&a);
printf("Value of n=%d",a);
fclose(fp);
return 0;
}[/c]
fclose(ptr)
. Compiler returns zero if the action is complete (or) returns eof
if there is any error in closing the file.
[c]
/* fclose example */
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","wt");
fprintf (pFile, "fclose example");
fclose (pFile);
return 0;
}
[/c] rename()
function.
remove()
function.