FILE HANDLING IN C What is a File

  • Slides: 45
Download presentation
FILE HANDLING IN C

FILE HANDLING IN C

What is a File? �A file is a collection of related data that a

What is a File? �A file is a collection of related data that a computers treats as a single unit. �Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. �When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. �In C language, we use a structure pointer of FILE type to declare a file. FILE is defined in stdio. h FILE library

Types of File 1. Text File: � Contains text in ASCII characters generally alphabets

Types of File 1. Text File: � Contains text in ASCII characters generally alphabets and numerics. � Human readable � Takes more space compared to binary files. 2. Binary File: � Contains text in binary form � Not Human readable � Faster access compared to text files.

Steps in Processing a File 1. Create a pointer variable pointing to the file

Steps in Processing a File 1. Create a pointer variable pointing to the file FILE *p; 2. Open the file using the FILE pointer created. 3. Read or write the data from/to the file. 4. Close the file using the FILE pointer

Basic file operations �fopen ()- open a file- specify how its opened (read/write) and

Basic file operations �fopen ()- open a file- specify how its opened (read/write) and type (binary/text) �fclose() - close an opened file �fread() - read from a file �fwrite ()- write to a file �fseek()/fsetpos() - move a file pointer to somewhere in a file. �ftell()/fgetpos ()- tell you where the file pointer is located.

File Open Modes w+ Write+read • Same as w mode • but in this

File Open Modes w+ Write+read • Same as w mode • but in this mode we can read and modify the data. r+ Read+write Same as ‘r’ mode but in this mode we can also write and modify existing data. a+ Append+read Same as ‘a’ mode But in this mode we can also read the data stored in the file.

More on File Open Modes

More on File Open Modes

Binary Mode To open a file in binary mode we can append ‘b’ to

Binary Mode To open a file in binary mode we can append ‘b’ to the mode �wb – binary file open in write mode �ab – binary file open in append mode

File Open �The file open function (fopen) fopen serves two purposes: �It makes the

File Open �The file open function (fopen) fopen serves two purposes: �It makes the connection between the physical file and the stream. �It creates “a program file structure to store the information” C needs to process the file. �Syntax: file pointer=fopen(“filename”, “mode”);

More On fopen() �The file mode tells C how the program will use the

More On fopen() �The file mode tells C how the program will use the file. �The filename indicates the system name and location for the file. �We assign the return value of fopen to our pointer variable: sp. Data = fopen(“MYFILE. TXT”, “w”); sp. Data = fopen(“A: \MYFILE. TXT”, “w”);

More On fopen

More On fopen

Closing a File �When we finish with a mode, we need to close the

Closing a File �When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. �To close a file, we use fclose and the pointer fclose variable: fclose(sp. Data);

fprintf() Syntax: fprintf (fp, "string", variables); It's just like printf() but output is sent

fprintf() Syntax: fprintf (fp, "string", variables); It's just like printf() but output is sent to a file, rather than standard output. It's used when we wish to store integers or floats in a file. The first argument is a pointer to file. Previous content of file are overwritten. Example: int i = 12; float x = 2. 356; char ch = 's'; FILE *fp; fp=fopen(“out. txt”, ”w”); fprintf (fp, "%d %f %c", i, x, ch);

fscanf() Syntax: fscanf (fp, "string", identifiers); Reads data from the file stream and stores

fscanf() Syntax: fscanf (fp, "string", identifiers); Reads data from the file stream and stores them according to the parameter format into the locations pointed by the additional arguments. Example: FILE *fp; Fp=fopen(“input. txt”, ”r”); int i; fscanf (fp, “%d", &i); scanf reads from stdin; fscanf reads from a user specified stream

getc() fgetc() Reads a single character from a given file and increment the file

getc() fgetc() Reads a single character from a given file and increment the file pointer position. Syntax: identifier = fgetc (file pointer); Example: FILE *fp; fp=fopen(“input. txt”, ”r”); char ch; ch = fgetc (fp);

putc() or fputc() write a single character to the output file, pointed to by

putc() or fputc() write a single character to the output file, pointed to by fp. Example: FILE *fp; char ch; fputc (ch, fp);

 C program to illustrate how a file stored on the disk is read

C program to illustrate how a file stored on the disk is read else #include <stdio. h> { #include <stdlib. h> printf(“Enter text: ”); void main() while((ch=getchar())!=EOF) { fputc(ch, fptr); FILE *fptr; } char filename[15]; ch = fgetc(fptr); char ch; while (ch != EOF) printf("Enter the filename to be opened { n"); printf ("%c", ch); scanf("%s", filename); ch = fgetc(fptr); /* open the file for reading */ } fptr = fopen(filename, “w+"); fclose(fptr); if (fptr == NULL) } { printf("Cannot open file n"); exit(0); }

C program to create a file called emp. rec and store information about a

C program to create a file called emp. rec and store information about a person void main() { FILE *fptr; char name[20]; int age; float salary; fptr = fopen ("emp. rec", "w"); /* open for writing*/ if (fptr == NULL) { printf("File does not exists n"); return; } printf("E nter the name n"); scanf("%s", name); fprintf(fptr, "Name = %sn", name); printf("Enter the age n"); scanf("%d", &age); fprintf(fptr, "Age = %dn", age); printf("Enter the salary n"); scanf("%f", &salary); fprintf(fptr, "Salary = %. 2 fn", salary); fclose(fptr); }

End of File There a number of ways to test for the end-of-file condition.

End of File There a number of ways to test for the end-of-file condition. �Usinf function feof() if (feof(fp)) printf("n End of file reached. "); � Another ways to use macro EOF. If(fgetc(fptr 1)==EOF) { printf ("End-of-file encountered. n”) ; }

#include <stdio. h> int main() { FILE *fp = fopen("test. txt", "r"); int ch

#include <stdio. h> int main() { FILE *fp = fopen("test. txt", "r"); int ch = getc(fp); while (ch != EOF) { /* display contents of file on screen */ putchar(ch); ch = getc(fp); } if (feof(fp)) printf("n End of file reached. "); else printf("n Something went wrong. "); fclose(fp); getchar(); return 0; }

fwrite() This function is used for writing an entire block to a given file.

fwrite() This function is used for writing an entire block to a given file. Entire block can be array or structure. Declaration: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) �ptr -- This is the pointer to the array of elements to be written. �size -- This is the size in bytes of each element to be written. �nmemb -- This is the number of elements to be written to the file. �stream -- This is the pointer to a FILE object that specifies an output stream.

Return Value This function returns the total number of elements successfully written is returned

Return Value This function returns the total number of elements successfully written is returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, it will show an error. #include<stdio. h> int main () { FILE *fp; char str[] = "This is gmail. com"; fp = fopen( "file. txt" , "w" ); fwrite(str , 1 , sizeof(str) , fp ); fclose(fp); return(0); }

fread () This function is used to read an antire block from a given

fread () This function is used to read an antire block from a given file. reads data from the given stream into the array pointed to by ptr. Declaration: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) � ptr -- This is the pointer to a block of memory with a minimum size of size*nmemb bytes. �size -- This is the size in bytes of each element to be read. �nmemb -- This is the number of elements, each one with a size of size bytes. �stream -- This is the pointer to a FILE object that specifies an input stream.

Return Value On succesfull it reads n items from the file and returns nmemb,

Return Value On succesfull it reads n items from the file and returns nmemb, if error or end of file occurs then it returns a value less than nmemb. int main() { FILE *fp; char c[] = "this is gmail. com"; char buffer[20]; /* Open file for both reading and writing */ fp = fopen("file. txt", "w+"); /* Write data to the file */ fwrite(c, 1, strlen(c) + 1, fp); /* Seek to the beginning of the file */ fseek(fp, 0 , SEEK_SET); /* Read and display data */ fread(buffer, 1, strlen(c)+1, fp); printf("%sn", buffer); fclose(fp); return(0); }

fseek() Description This function is used for setting the file position pointer at the

fseek() Description This function is used for setting the file position pointer at the specified byte. Declaration int fseek(FILE *fp, long int offset, int origin) Parameters �fp -- This is the pointer to a FILE object that identifies the stream. �offset -- This is the number of bytes to offset from origin. �origin -- This is the position from where offset is added. It is specified by one of the following constants: SEEK_SET Seeks from beginning of file SEEK_CUR Seeks from current position SEEK_END Seeks from end of file

Return Value This function returns zero if successful, else it returns nonzero value. #include

Return Value This function returns zero if successful, else it returns nonzero value. #include <stdio. h> int main () { FILE *fp; fp = fopen("file. txt", "w+"); fputs("This is tutorialspoint. com", fp); fseek( fp, 7, SEEK_SET ); fputs(" C Programming Langauge", fp); fclose(fp); return(0); } O/p This is C Programming Langauge

PROGRAM 7 -3 Read and Print Text File of Integers Computer Science: A Structured

PROGRAM 7 -3 Read and Print Text File of Integers Computer Science: A Structured Programming Approach Using C 27

PROGRAM 7 -3 Read and Print Text File of Integers Computer Science: A Structured

PROGRAM 7 -3 Read and Print Text File of Integers Computer Science: A Structured Programming Approach Using C 28

#include <stdio. h> #include <stdlib. h> int main() { char str 1[10]=“WE”, str 2[10]=“

#include <stdio. h> #include <stdlib. h> int main() { char str 1[10]=“WE”, str 2[10]=“ are”, str 3[10]=“in”; int year=2012; FILE * fp; fp = fopen ("file. txt", "w+"); fscanf(fp, "%s %s %s %d", str 1, str 2, str 3, &year); printf("Read String 1 |%s|n", str 1 ); printf("Read String 2 |%s|n", str 2 ); printf("Read String 3 |%s|n", str 3 ); printf("Read Integer |%d|n", year ); fclose(fp); return(0); }

Writing to a file #include <stdio. h> int main() { int n; FILE *fptr;

Writing to a file #include <stdio. h> int main() { int n; FILE *fptr; fptr=fopen("program. txt", "w"); if(fptr==NULL) { printf("Error!"); exit(1); } printf("Enter n: "); scanf("%d", &n); fprintf(fptr, "%d", n); fclose(fptr); return 0; } Reading from file #include <stdio. h> int main() { int n; FILE *fptr; if((fptr=fopen(“program. txt", "r"))==NULL) { printf("Error! opening file"); exit(1); } fscanf(fptr, "%d", &n); printf("Value of n=%d", n); fclose(fptr); return 0; }

PROGRAM 7 -4 Copy Text File of Integers Computer Science: A Structured Programming Approach

PROGRAM 7 -4 Copy Text File of Integers Computer Science: A Structured Programming Approach Using C 31

PROGRAM 7 -4 Copy Text File of Integers Computer Science: A Structured Programming Approach

PROGRAM 7 -4 Copy Text File of Integers Computer Science: A Structured Programming Approach Using C 32

PROGRAM 7 -4 Copy Text File of Integers Computer Science: A Structured Programming Approach

PROGRAM 7 -4 Copy Text File of Integers Computer Science: A Structured Programming Approach Using C 33

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 34

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 34

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 35

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 35

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 36

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 36

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 37

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 37

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 38

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 38

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 39

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 39

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 40

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 40

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 41

PROGRAM 7 -6 Student Grades Computer Science: A Structured Programming Approach Using C 41

#include <stdio. h> #include <stdlib. h> int main(void) { FILE *fp; char s[80]; int

#include <stdio. h> #include <stdlib. h> int main(void) { FILE *fp; char s[80]; int t; if((fp=fopen("test", "w")) == NULL) { printf("Cannot open file. n"); exit(1); } printf("Enter a string and a number: "); fscanf(stdin, "%s%d", &s, &t); fprintf(fp, "%s %d", s, t); fclose(fp); if((fp=fopen("test", "r")) == NULL) { printf("Cannot open file. n"); exit(1); } fscanf(fp, "%s%d", s, &t); fprintf(stdout, "%s %d", s, t); return 0; } /* read from keyboard */ /* write to file */ /* read from file */ /* print on screen */

File Copy Program #include <stdio. h> #include <stdlib. h> gets(target_file); target = fopen(target_file, "w");

File Copy Program #include <stdio. h> #include <stdlib. h> gets(target_file); target = fopen(target_file, "w"); int main() { if( target == NULL ) char ch, source_file[20], target_file[20]; { FILE *source, *target; fclose(source); printf("Press any key to exit. . . n"); printf("Enter name of file to copyn"); exit(EXIT_FAILURE); gets(source_file); } while( ( ch = fgetc(source) ) != EOF ) source = fopen(source_file, "r"); fputc(ch, target); if( source == NULL ) { printf("Press any key to exit. . . n"); exit(EXIT_FAILURE); } printf("Enter name of target filen"); printf("File copied successfully. n"); fclose(source); fclose(target); return 0; }

Reading and Writing Files #include <stdio. h> int main ( ) { FILE *outfile,

Reading and Writing Files #include <stdio. h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13. 72, c = 6. 68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile, "%f %d %f", &e, &f, &g) ; printf (“ %f %d %f n ", a, b, c) ; printf (“ %f %d %f n ", e, f, g) ; }

Example #include <stdio. h> #include<conio. h> void main() { char ch; FILE *fp; fp=fopen("out.

Example #include <stdio. h> #include<conio. h> void main() { char ch; FILE *fp; fp=fopen("out. txt", "r"); while(!feof(fp)) { ch=getc(fp); printf("n%c", ch); } getch(); }