


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A comprehensive guide to file handling in c programming, covering topics such as opening, closing, reading from, and writing to files. It includes explanations of text and binary files, along with practical code examples demonstrating how to use functions like fopen(), fclose(), fprintf(), fscanf(), fread(), and fwrite(). The document also discusses file positioning functions and provides examples of reading and writing structures using binary files. It is suitable for high school students learning about file handling in c.
Typology: Lecture notes
1 / 26
This page cannot be seen from the preview
Don't miss anything!



















Unit-III Preprocessor: The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros. The C preprocessor provides following type:
#else and #if in one statement. 9 #endif Ends preprocessor conditional. Header Files: (#include) A header file is a file containing C declarations and macro definitions. we request the use of a header file in our program with the C preprocessing directive #include'. The header files names end with.h'. Both user and system header files are included using the preprocessing directive `#include'
int a,b,area; printf(“enter a & b value\n”); scanf(“%d%d”,&a,&b); area=rectanglearea(a,b); printf(“area of rectangle is %d\n”,area); } Output: Enter a & b value 2 5 area of rectangle is 10 Miscellaneous Directives: (#undef) the #undef directive tells the preprocessor to remove the definitions for the specified macro. A macro can be redefined after it has been removed by the #undef directive. Syntax: #undef Template_name(Arguments,...) (Expression) Example:
Example 1: #include
int main() { int a=2,b=11; printf("area of rectangle is %d", area(a,b)); return 0; } Output: Error // area is not defined macro Example 2: #include
int main() { int a=2,b=11; printf("area of rectangle is %d", area(a,b)); return 0; } Output: area of rectangle is 22 Conditional compilation : (#ifdef, #ifndef, #endif) Using conditional compilation, if user want, compiler to skip over part of code by using preprocessing commands #ifdef and #endif Syntax: #ifdef macroname Statement 1; Statement 1; . . #endif If macronme has been #defind, the block of code will be processed as usual; otherwise not.
Output: end of the program #if, #else, #elif, #endif Directives: The #if directive is used to test whether an expression evaluate to a nonzero value or not. If result is non zero(ie true) the subsequent line of code execute upto #else, #elif or #endif comes; otherwise they are skipped. Example: check number is +ve, - ve or zero. #include int main() { int num; printf("enter number"); scanf("%d",&num); #if num> printf("number is +ve\n"); #elif num< printf("number is - ve\n"); #else printf("number is zero\n"); #endif return 0; } Output: enter number 25 number is +ve File:
In C programming, file is a place on computer disk where information is stored permanently. Which represents a sequence of bytes ending with an end-of- file marker(EOF). Why files are needed?
fp= fopen(“filename”, “mode”); filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types, Example: fp= fopen(“sample.txt”, “w”); fp= fopen(“sample.txt”, “r”); mode description r opens a text file in reading mode w opens or create a text file in writing mode. a opens a text file in append mode r+ opens a text file in both reading and writing mode w+ opens a text file in both reading and writing mode a+ opens a text file in both reading and writing mode rb opens a binary file in reading mode wb opens or create a binary file in writing mode ab opens a binary file in append mode rb+ opens a binary file in both reading and writing mode wb+ opens a binary file in both reading and writing mode ab+ opens a binary file in both reading and writing mode If fopen( ) cannot open "test.dat " it will a return a NULL pointer which should always be tested for as follows. Example: FILE *fp ;
if ( ( fp = fopen( "test.dat", "r" ) ) == NULL ) { puts( "Cannot open file") ; exit( 1) ; } This will cause the program to be exited immediately if the file cannot be opened. Closing a File: The file (both text and binary) should be closed after reading/writing. Closing a file is performed using library function fclose(). Syntax: fclose(file_pointer_name); Example: fclose(fp); //fp is the file pointer associated with file to be closed Reading and writing to a text file: For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE. Writing to a text file: Example 1: Write to a text file using fprintf() #include int main() { int num; FILE *fptr; fptr = fopen("program.txt","w"); if(fptr == NULL) { printf("Error!"); exit( 1 );
Note: Other functions like fgetchar(), fgetc(),fputc(),fgets(),fputs() etc. can be used in similar way. 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 function fwrite(). The functions takes four arguments: Address of data to be written in disk, Size of data to be written in disk, number of such type of data and pointer to the file where you want to write. fwrite(address_data,size_data,numbers_data,pointer_to_file); Example 3: Writing to a binary file using fwrite() #include 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 = 5n;
num.n3 = 5n + 1 ; fwrite(&num, sizeof(struct threeNum), 1 , fptr); } fclose(fptr); return 0 ; } In this program, you create a new file program.bin in the C drive. 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 fwrite() function as above. fread(address_data,size_data,numbers_data,pointer_to_file); Example 4: Reading from a binary file using fread() #include struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr;
if ( ( fin = fopen( source, "rb" ) ) == NULL ) { puts( "Cannot open input file ") ; puts( source ) ; exit( 1 ) ; } // open as binary as we don’t know what is in file if ( ( fout = fopen( dest, "wb" ) == NULL ) ) { puts( "Cannot open output file ") ; puts( dest ) ; exit( 1 ) ; } while ( ( ch = fgetc( fin ) ) != EOF ) fputc( ch , fout ) ; fclose( fin ) ; fclose( fout ) ; } Note : When any stream I/O function such as fgetc() is called the current position of the file pointer is automatically moved on by the appropriate amount, 1 character/ byte in the case of fgetc() ; Appending Data To Existing File Append mode is used to append or add data to the existing data of file (if any). Hence, when you open a file in Append (a) mode , the cursor is positioned at the end of the present data in the file. In general, to append is to join or add on to the end of something. For example, an appendix is a section appended (added to the end) of a document. In computer programming , append is the name of a procedure for concatenating (linked) lists or arrays in some high- level programming languages. FILE *pFile; FILE *pFile2; char buffer[ 256 ]; pFile=fopen("myfile.txt", "r"); pFile2=fopen("myfile2.txt", "a"); if(pFile==NULL) { perror("Error opening file."); } else { while(fgets(buffer, sizeof(buffer), pFile)) { fprintf(pFile2, "%s", buffer); }
} fclose(pFile); fclose(pFile2);
Read , write and seek operations can be performed on binary files with the help of fread(), fwrite() and fseek() functions, respectively. After reading or writing a structure , the file pointer is moved to the next structure. The fseek() function can move the pointer to the position as requested
Binary files are very similar to arrays except for the fact that arrays are temporary storage in the memory but binary files are permanent storage in the disks. The most important difference between binary files and a text file is that in a binary file, you can seek , write , or read from any position inside the file and insert structures directly into the files. You must be wondering - why do we need binary files when we already know how to handle plaintexts and text files? Here are the reasons why binary files are necessary :
Usually, large text files contain millions of numbers. It takes a lot of time to convert 32 - bit integers to readable characters. This conversion is not required in the case of binary files as data can be directly stored in the form of bits.
For data that is in the form of images, audio or video, this is very important. Small size means less storage space and faster transmission. For example, a storage device can store a large amount of binary data as compared to data in character format.
For example, Java compilers generate bytecodes after compilation. Having said that, let's move on to handling I/O operations in a binary file in C. The basic parameters that the read and write functions of binary files accept are:
Pointer position: This sets the pointer position in the file. Value pointer position 0 Beginning of file. 1 Current position 2 End of file **Example:
Example: Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we need fseek() and fgetc()). 01 #include 02 #include 03 void main() 04 { 05 FILE *fp; 06 char ch; 07 clrscr(); 08 fp=fopen("file1.c", "r"); 09 if(fp==NULL) 10 printf("file cannot be opened"); 11 else 12 { 13 printf("Enter value of n to read last ‘n’ characters"); 14 scanf("%d",&n); 15 fseek(fp,-n,2); 16 while((ch=fgetc(fp))!=EOF) 17 { 18 printf("%c\t",ch); 19 } 20 } 21 fclose(fp);