Documente Academic
Documente Profesional
Documente Cultură
What is afile?
1. Sequential file.
“w”-means write to the file, if the file mane exist already then it is deleted and a new file will be created.
“r”-means read from a file. If the file does not exist, error is returned, i.e., NULL is returned as the value
of fopen.
“a”-means append a file. New data are added to the end of the file.
Write a program to copy the content of a file to append the content into another file.
#include<stdio.h>
main()
{
int alpha;
file *fr,*fw,*fa;
fr=fopen(“ss.doc”, “r”); /* existing file to be copied to another file*/
fw=fopen(“ws.doc”, “w”); /*copy the content of ss.doc to ws.doc*/
fa=fopen(“as.doc”, “a”); /*append the content of ss.doc to as.doc*/
do
{
alpha=fgetc(fr);
fputc(alpha,fw);
fputc(alpha,fa);
putchar(alpha);
}
while(alpha!=eof);
fclose(fr);
fclose(fw);
fclose(fa);
}
Write a program to delete a file.
#include<stdio.h>
#include<fcntl.h>
main()
{
file *in_file
char s[20];
printf(“file name?\n”);
scanf(“%s”, s);
if((in_file=fopen(s, “r”))==null)
{
printf(“no such a file exist \n”);
exist();
}
else
unlink(s);
}
1.The fread() function is used to read a block of binary data from a given file. It is also used to read one
or more stuctures from a given file and copies them to given memory location. The general format of the
fread function is as follows:
The ptr may be a pointer to a variable of any type (from a single character to a structure). The size, an
integer, should give the numbers of bytes in each item.
#include<stdio.h>
main()
{
file *out_file;
struct database {
char name[20];
int age;
}; /*the structure can be defined within or outside of the
main function*/
struct database person;
……………………………
…………………………………
fread(&person,sizeof(person),2,out_file);
……………………………………….
………………………………………..
fclose(out_file);
}
Fread() function does not explicity indicate errors. So that feof() and ferror() functions should be used to
detect end of the files or errors.
2.The fwrite() function is used to write a binary data to a given file. It is also used to write one or more
structures to a given file. The general format of fwrite() function is as follows:
fwrite(ptr,size,nitems,fptr)
The ptr may be a pointer to a variable of any types(from a single character to a structure). The size should
give the number of bytes in each item to be written. The fwrite() function always returns the number of
items actually written to the file whether a not of end of the file or an error is encountered.
#include<stdio.h>
{
file *out_file;
struct database {
char mane[20];
int age;
}; /* the structure can be defined within or outside of the main
function*/
struct database person;
…………………………………..
…………………………………..
fwrite(&person,sizeof(person),2,out_file);
…………………………………..
…………………………………..
fclose(out_file);
}