90 likes | 256 Views
File Handling. Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University. Your vision? Seek with all your heart?. Unit Learning Objectives. Explain the concept pf data files Explain different types of files. Types of Files. Three categories of files
E N D
File Handling Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University
Your vision? Seek with all your heart? Unit Learning Objectives • Explain the concept pf data files • Explain different types of files Code Optimization
Types of Files • Three categories of files • Text files • Formatted files • Binary files Introduction
Common Functions • Define a File pointer • FILE *fp • Open a File • Fopen(“filename, “mode” • R, w, a, r+, w+, a+ • Close a File • Fclose(fp) • Perform operations • Fscanf() • fprintf() • Fgetc() • Fputc() Introduction
Create a file #include <stdio.h> main() { FILE *fp; fp= fopen(“test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fputc(ch, fp); fclose(fp); } Introduction
Read a file int main () { FILE *fp; int c; fp= fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); } Introduction
Merging command line arguments /* fgetsexmaple */ #include <stdio.h> intmain(intarg, char *argv[]) { FILE * pFile; char string [BUFSIZ]; pFile = fopen (argv[1] , "r"); if (pFile == NULL) perror ("Error opening file"); else { while (fgets (string , BUFSIZ, pFile) != NULL) { puts (string); } fclose (pFile); } return 0; } Introduction