File Processing: Subject: COMP6047 Algorithm and Programming Year: 2019
File Processing: Subject: COMP6047 Algorithm and Programming Year: 2019
File Processing
Learning Outcomes
At the end of this session, student will be able to:
• Demonstrate ability to apply file read, write data to a text file or
binary (LO2, LO3 & LO4)
• Syntax:
FILE *fp;
Where fp is a file pointer pointing to the start of the buffer area.
• fputc (OUTPUT)
– Writing one character to a file
– fputc('a', stdout) similar with putchar( 'a' )
– Syntax: int fputc( int c, FILE *stream );
– Return a character when successful, and EOF if error
• fputs (OUTPUT)
– Writing a line to a file
– Syntax: int fputs( const char *string, FILE *stream );
– Return non-negative value while successful and EOF if error.
• fprintf (OUTPUT)
– Syntax:
int fprintf( FILE *stream, const char *format [, argument ]...);
– Writing data to a file using the printf format.
– Return number of byte written if successful and negative value if
error.
#include <stdio.h>
int main(void)
{
FILE *fp;
int Arr[]={1,2,3,4,5};
fp=fopen("test.dat","w");
if(fp==NULL){
printf("File test.dat can’t be created\n");
exit(1);
}
fwrite(Arr,sizeof(Arr),1,fp);
fclose(fp);
return 0;
}
COMP6047 - Algorithm and Programming 27
Program Examples
• Example reading data from binary file test.dat using fread
#include <stdio.h>
int main(void)
{
FILE *fp; int i;
int Arr[5];
fp=fopen("test.dat","r");
if(fp==NULL){
printf("File test.dat can’t be opened\n");
exit(1);
}
fread(Arr,sizeof(Arr),1,fp);
for(i=0; i<5; i++) printf("%d ",Arr[i]);
fclose(fp);
return 0;
}