UNIT 5 File: The file is to store the available data or info in a file with the help of a program. It stores all the data available in a program into a file with the help of file handling in C. The data can be fetched / extracted from these files to work again in any program. (Or) A file refers to a source in which a program stores the information/data in the form of bytes of sequence on a disk (permanently). The content available on a file isn’t volatile like the compiler memory in C. But the program can perform various operations, such as creating, opening, reading a file, or even manipulating the data present inside the file. Why Files: Reusability: File handling allows us to preserve the information/data generated after we run the program. Saves Time: Some programs might require a large amount of input from their users. In such cases, file handling allows you to easily access a part of a code using individual commands. Commendable storage capacity: When storing data in files, you can leave behind the worry of storing all the info in bulk in any program. Portability: The contents available in any file can be transferred to another one without any data loss in the computer system. This saves a lot of effort and minimizes the risk of flawed coding. Types of Files in a C Program: Files are available in 2 distinct forms, namely: 1. Text Files 2. Binary Files 1. Text Files: Text files are created using an extension .txt with the help of a simple text editor. In general, we can use notepads for the creation of .txt files. These files store info internally in ASCII character format, but when we open these files, the content/text opens in a human-readable form. Disadvantage: it lacks security. consume a very large space in storage. 2. Binary Files The binary files store info and data in the binary format of 0’s and 1’s (the binary number system). The files occupy comparatively lesser space in the storage. In simple words, the binary files store data and info the same way a computer holds the info in its memory. Operators/Functions for file in c: Description of Function Function in Use used to open an existing file or a new file fopen() writing data into an available file fprintf() reading the data available in a file fscanf() writing any character into the program file fputc() reading the character from an available file fgetc() used to close the program file fclose() used to set the file pointer to the intended file position fseek() writing an integer into an available file fputw() used to read an integer from the given file fgetw() used for reading the current position of a file ftell() sets an intended file pointer to the file’s beginning itself rewind() Declare a file-type pointer when we are working with various files in a program. This helps establish direct communication between a program and the files. Syntax: FILE *fpointer; Operations in Files: Opening a file that already exists Creating a new file Reading content/ data from the existing file Writing more data into the file Deleting the data in the file or the file altogether Opening Modes of C in Standard I/O of a Program Mode in Program Meaning of Mode When the file doesn’t exist r Open a file for reading the content. In case the file doesn’t exist in the location, then fopen() will return NULL. rb Open a file for reading the content in binary mode. In case the file doesn’t exist in the location, then fopen() will return NULL. w Open a file for writing the content. In case the file exists, its contents are overwritten. In case the file doesn’t exist in the location, then it will create a new file. wb Open a file for writing the content in binary mode. In case the file exists, then its contents will get overwritten. In case the file doesn’t exist in the location, then it will create a new file. a Open a file for appending the content. Meaning, the data of the program is added to the file’s end in a program. In case the file doesn’t exist in the location, then it will create a new file. ab Open a file for appending the content in binary mode. Meaning, the data of the program is added to the file’s end in a program in a binary mode. In case the file doesn’t exist in the location, then it will create a new file. r+ Open a file for both writing and reading the content. In case the file doesn’t exist in the location, then fopen() will return NULL. rb+ Open a file for both writing and reading the content in binary mode. In case the file doesn’t exist in the location, then fopen() will return NULL. w+ Open a file for both writing and reading. In case the file exists, its contents are overwritten. In case the file doesn’t exist in the location, then it will create a new file. wb+ Open a file for both writing and reading the content in binary mode. In case the file exists, its contents are overwritten. In case the file doesn’t exist in the location, then it will create a new file. a+ Open a file for both appending and reading the content. In case the file doesn’t exist in the location, then it will create a new file. ab+ Open a file for both appending and reading the content in binary mode. In case the file doesn’t exist in the location, then it will create a new file. To open a file: fptr = fopen (“openfile/filename” , “openingmode”); To close a file: fclose(fptr); Create a File: int main() { FILE *fptr; // Create a file on your computer (filename.txt) fptr = fopen("filename.txt", "w"); /* to create the file in a specific folder, provide exact path fptr = fopen("C:\directoryname\filename.txt", "w");*/ // Close the file fclose(fptr); return 0; } Output: Write To Files: #include <stdio.h> int main() { FILE *fptr; // Open a file in writing mode fptr = fopen("filename.txt", "w"); // Write some text to the file fprintf(fptr, "Some text"); // Close the file fclose(fptr); return 0; } Output: Note: If you write to a file that already exists, the old content is deleted, and the new content is inserted. #include <stdio.h> int main() { FILE *fptr; // Open a file in writing mode fptr = fopen("filename.txt", "w"); // Write some text to the file fprintf(fptr, "Hello World!"); // Close the file fclose(fptr); return 0; } Output: Append Content to a File: #include <stdio.h> int main() { FILE *fptr; // Open a file in append mode fptr = fopen("filename.txt", "a"); // Append some text to the file fprintf(fptr, "\nHi everybody!"); // Close the file fclose(fptr); return 0; } Output: Read Files: Now create a string that should be enough to store the content of the file. For example, create a string that can store up to 100 characters: To read the content of filename.txt, we can use the fgets() function which takes three parameters: The first parameter specifies where to store the file content, which will be in the myString array we just created. The second parameter specifies the maximum size of data to read, which should match the size of myString (100). The third parameter requires a file pointer that is used to read the file (fptr in our example). #include <stdio.h> int main() { FILE *fptr; // Open a file in read mode fptr = fopen("filename.txt", "r"); // Store the content of the file char myString[100]; // Read the content and store it inside myString fgets(myString, 100, fptr); // Print file content printf("%s", myString); // Close the file fclose(fptr); return 0; } Output: Hello World! Note: The fgets function only reads the first line of the file. If there were more number of lines of text in filename.txt then to read every line of the file, use a while loop: While(fgets(myString, 100, fptr)) { // Print file content printf("%s", myString); } Note: open a file that does not exist, then fopen() function will return NULL. #include <stdio.h> int main() { FILE *fptr; // Open a file in read mode fptr = fopen("loremipsum.txt", "r"); // Print some text if the file does not exist if(fptr == NULL) { printf("Not able to open the file."); } // Close the file fclose(fptr); return 0; } Output: Not able to open the file. Writing and reading structures using binary files: Reading and writing to a binary file: Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files. Writing to a binary file To write into a binary file, you need to use the fwrite() function. The functions take four arguments: address of data to be written in the disk size of data to be written in the disk number of such type of data pointer to the file where you want to write. fwrite(addressData, sizeData, numbersData, pointerToFile); Example : Write to a binary file using fwrite() #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","wb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0; } We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num. Now, inside the for loop, we store the value into the file using fwrite(). The first parameter takes the address of num and the second parameter takes the size of the structure threeNum. Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data. Finally, we close the file. Reading from a binary file Function fread() also take 4 arguments similar to the fwrite() function as above. fread(addressData, sizeData, numbersData, pointerToFile); Example : Read from a binary file using fread() #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","rb")) == NULL) { printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3); } fclose(fptr); return 0; } In this program, you read the same file program.bin and loop through the records one by one. In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num. number of build-in function to perform basic file operations: fopen() - create a new file or open a existing file fclose() - close a file getc() - reads a character from a file putc() - writes a character to a file fscanf() - reads a set of data from a file fprintf() - writes a set of data to a file getw() - reads a integer from a file putw() - writes a integer to a file fseek() - set the position to desire point ftell() - gives current position in the file rewind() - set the position to the beginning point Random access using fseek(), ftell() and rewind() functions: fseek() - It is used to moves the reading control to different positions using fseek function. Syntax: int fseek(FILE *fp, long int offset, int origin); Here fp is the file pointer of the stream on which I/O operations are carried on; offset is the number of bytes to skip over. The offset can be either positive or negative, denting forward or backward movement in the file. Origin is the position in the stream to which the offset is applied; this can be one of the following constants: SEEK_SET : offset is relative to beginning of the file SEEK_CUR : offset is relative to the current position in the file SEEK_END : offset is relative to end of the file Example: #include <stdio.h> void main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is pps", fp); fseek( fp, 7, SEEK_SET ); fputs("welcome to AI", fp); fclose(fp); } Output: welcome to AI ftell() - It tells the byte location of current position in file pointer. Syntax: int ftell(FILE *fp); Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or a positive integer indicating the byte offset from the beginning of an open file. A return value of -1 indicates an error. Example: #include <stdio.h> #include <conio.h> void main (){ FILE *fp; int length; clrscr(); fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("Size of file: %d bytes", length); getch(); } Output: Size of file: 21 bytes rewind() - It moves the control to beginning of a file. The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream many times. Syntax: void rewind(FILE *stream) Example: #include void main(){ FILE *fp; int i; clrscr(); fp = fopen("CHAR.txt","r"); for (i=1;i<=10;i++){ printf("%c : %d\n",getc(fp),ftell(fp)); fseek(fp,ftell(fp),0); if (i == 5) rewind(fp); } fclose(fp); } Output: W:0 e:1 l:2 c:3 o:4 W:0 e:1 l:2 c:3 o:4 Example Programs: A program to write integer data into file and read it from file Program: #include<stdio.h> main() { int num; FILE *f2; f2=fopen("data.int","w"); scanf("%d",&num); putw(num,f2); fclose(f2); f2=fopen("data.int","r"); num=getw(f2); printf("%d",num); fclose(f2); } Output: 12 12 Program to copy one file contents to another Program: #include <stdio.h> #include <process.h> void main(int argc, char *argv[]) { FILE *fs,*ft; char ch; if(argc!=3) { puts("Invalid number of arguments."); exit(0); } fs = fopen(argv[1],"r"); if(fs==NULL) { puts("Source file cannot be opened."); exit(0); } ft = fopen(argv[2],"w"); if (ft==NULL) // check the condition if the file pointer is NULL or not { puts("Target file cannot be opened."); fclose(fs); exit(0); } while(1) { ch=fgetc(fs); if (ch==EOF) // check the condition if the file is end or not break; else fputc(ch,ft); } fclose(fs); fclose(ft); getch(); } Output: source.c this is source text ouput.c Command line arguments source.c ouput.c source.c this is source text ouput.c this is source text Command line arguments source.c Invalid number of arguments. Program to reverse the first n characters in a file Program: #include <stdio.h> #include <string.h> #include <process.h> void main(int argc, char *argv[]) { char a[15]; char s[20]; char n; int k,j=0,i,len; FILE *fp; if(argc!=3) { puts("Improper number of arguments."); exit(0); } fp = fopen(argv[1],"r"); if(fp == NULL) { puts("File cannot be opened."); exit(0); } k=*argv[2]-48; n = fread(a,1,k,fp); a[n]='\0'; len=strlen(a); for(i=len-1;i>=0;i--) { s[j]=a[i]; printf("%c",s[j]); j=j+1; } s[j+1]='\0'; getch(); } Output: source.c this is source ouput.c Command line arguments source.c ouput.c source.c this is source ecruos si siht Command line arguments source.c Invalid number of arguments. (v) A program to write product details Program: #include<stdio.h> main() { char c[20]; int p,q,b; FILE *f2; f2=fopen("data.dat","w"); printf("enter item name,price, quantity"); scanf("%s%d%d",&c,&p,&q); b=p*q; printf("%s%d%d%d",c,p,q,b); fclose(f2); } Output: Enter item name, price, quantity Rice 25 1 Rice 25 1 25 fscanf () and fprintf() with syntax. Writing File : fprintf() function The fprintf() function is used to write set of characters into file. It sends formatted output to a stream. Syntax: int fprintf(FILE *stream, const char *format [, argument, ...]) Reading File : fscanf() function The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file. Syntax: int fscanf(FILE *stream, const char *format [, argument, ...]) fgetc() and fputc() with syntax. fgetc() The function fgetc() is used to read the character from the file. It returns the character pointed by file pointer, if successful otherwise, returns EOF. Syntax: int fgetc(FILE *stream) fputc() The function fputc() is used to write the character to the file. It writes the character to the file, if successful otherwise, returns EOF. Syntax: int fputc(int character, FILE *stream) char − The character is to be written to the file. stream − This is the pointer to the file where character is to be written. #include <stdio.h> void main() { FILE *f; f = fopen("new.txt", "w"); fputc('a',f); fclose(f); } Output: A getw() and putw() with syntax. getw() and putw() are similar to getc() and putc(). The only difference is that getw() and putw() are especially meant for reading and writing the integer data. getw() getw() is use to read the integer data from the file. Syntax: int getw(FILE*); Example: int main() { FILE *fp; int ch; fp=fopen("file1.txt","r"); ch=getw(fp); printf("%d",ch); fclose(fp); } putw() putw() is use to write integer data on the file (text file). Syntax: int putw(integer, FILE*); Example: int main() { FILE *fp; fp=fopen("file1.txt","w"); putw(65,fp); fclose(fp); }