You are on page 1of 2

14 ‫שיעור‬

Creating a file and output some data
/* Program to create a file and write some data the file */ #include <stdio.h> main( ) { FILE *fp; char stuff[25]; int index; fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line."); for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %d\n", stuff, index); fclose(fp); /* close the file before ending program */ }

Reading (r)
/* Program to display the contents of a file on screen */ #include <stdio.h> void main() { FILE *fp; char c; fp = fopen("prog.c","r"); c = fgetc(fp) ; while (c!= EOF) { putchar(c); c = fgetc(fp); } fclose(fp); }

Closing a file
#include <stdio.h> int main( ) { FILE *fp; char c; fp = fopen("TENLINES.TXT", "r"); if (fp == NULL) printf("File doesn't exist\n"); else { c = fgetc(fp); /* get one character from the file*/ do { putchar(c); /* display it on the monitor*/ c = fgetc(fp); /* get one character from the file*/ } while (c != EOF); /* repeat until EOF (end of file)*/ } fclose(fp); return(0); }

Reading Line after Line
/* Program to display the contents of a file on screen */ #include <stdio.h> void main() { FILE *fp; char c[80]; fp = fopen("new1.txt","r"); while ( fgets(c,70,fp)!=NULL) { printf("%d\n",strlen(c)); //c has inside also \n, it will count it printf("%d\n",c[strlen(c)-1]); //will print 10 printf("%s",c); //will print the line and will go jump down } fclose(fp); }

Writing to file Line by Line
#include <stdio.h> int main( ) { FILE *r_fp; FILE *w_fp; char c[80]; r_fp = fopen("TENLINES.TXT","r"); w_fp = fopen("TENLINES1111.TXT", "w"); if (r_fp == NULL|| r_fp == NULL ) printf("File doesn't exist\n"); else{ while ( fgets(c,80,r_fp)!=NULL){ printf("%s",c); fputs(c, w_fp); } } fclose(r_fp); fclose(w_fp); return(0); }