File Management, Pre-processors and Bit-wise operators PDF

Summary

These notes cover file management, pre-processors and bit-wise operators in C programming. It explains how to handle files including creating, opening, reading, and writing files. It also discusses pre-processor directives and bitwise operators with code examples.

Full Transcript

B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators File handling File handling in C stores data of our program to our local storage which can be used at any time because as the execution of a program completes our data is lost. Therefore, here comes the need t...

B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators File handling File handling in C stores data of our program to our local storage which can be used at any time because as the execution of a program completes our data is lost. Therefore, here comes the need to save our data in any file form - text files or binary files. File Handling is the storing of data in a file using a program. In C programming language, the programs store results, and other data of the program to a file using file handling in C. Also, we can extract/fetch data from a file to work with it in the program. The operations that you can perform on a File in C : −  Creating a new file  Opening an existing file  Reading data from an existing file  Writing data to a file  Moving data to a specific location on the file  Closing the file Types of Files in C We will be working with two types of files: - 1. Text file 2. Binary file Text file - User can create these types of files easily while dealing with file handling in C. It stores information in the form of ASCII characters internally and when the file is opened, the content is readable by humans. It can be created by any text editor with a.txt or.rtf (rich text) extension. Since text 1 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators files are simple, they can be edited by any text editor like Microsoft Word, Notepad, Apple Text edit etc. Binary file - It stores information in the form of 0’s or 1’s and it is saved with.bin extension, therefore it takes less space. Since it is stored in the format of a binary number system it is not readable by humans. Therefore, it is more secure than a text file. File Handling Functions in C Now, we will be talking about different file handling functions. Function Description Syntax Used to open an existing file or to fopen() FILE *fopen(“file_name”, “mode”); create a new file fprintf(FILE *stream, const char fprintf() Used to write data in existing file *format [, argument,...]) fscanf(FILE *stream, const char fscanf() Used to read data from the file *format [, argument,...]) fputc() Used to write characters in a file fputc(int c, FILE *stream) Used to read characters from a fgetc() fgetc(FILE *stream) file fclose() Used to close existing file fclose( FILE *fp ) puts the file pointer to the fseek(FILE *stream, long int offset, fseek() specified place int whence) Used to write integral value in fputw() fputw(int number,File *fp) the file fgetw() Used to read integral value from fgetw(File *fp) 2 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Function Description Syntax the file It will return the current position ftell() ftell(FILE *stream) of the file pointer in the file the file pointer is set to the start rewind() rewind(FILE *stream) of the file Modes to Open a File in C To open a file we use fopen() with different opening modes. The most common modes used are listed below. Mode Description Example R opens a text file in read-only mode fopen(“demo.txt”, “r”) W opens a text file in the write-only mode fopen(“demo.txt”, “w”) A opens a text file in append mode fopen(“demo.txt”, “a”) r+ opens a text file in read and write mode fopen(“demo.txt”, “r+”) w+ opens a text file in read and write modes fopen(“demo.txt”, “w+”) a+ opens a text file in read and write modes fopen(“demo.txt”, “a+”) Rb opens a binary file in read mode. fopen(“demo.txt”, “rb”) wb opens a binary file in write mode. fopen(“demo.txt”, “wb”) Ab opens a binary file in append mode fopen(“demo.txt”, “ab”) rb+ opens a binary file in read and write modes fopen(“demo.txt”, “rb+”) wb+ opens a binary file in read and write modes fopen(“demo.txt”, “wb+”) 3 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Mode Description Example ab+ opens a binary file in read and write modes fopen(“demo.txt”, “ab+”) [Notes: In append mode, we can write data into an existing file without deletion of existing contents whereas in write mode existing data is deleted which was already present in the file.] Creating a new file We use the fopen() function to create a new file as well as open an existing file in our storage. The syntax of fopen()- fopen("filename","mode") When declaring a file in C, the pointer of the file type (FILE) is used to point the file. fopen() will give the address of the file to the file pointer which is going to create/open. Let's create a new file with the name BCA.txt. #include int main() { FILE * file; file = fopen("BCA.txt","w"); } A new file will be created in the folder where your code is saved. You can also specify the path where you want your file to be created. file = fopen ("C://BCA.txt", "w"); We use write mode because it will create a new file if the file is not present. 4 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Opening an Existing File To open an existing file we use fopen() with the required opening modes We have already created a file using write mode. In the following code, user mode that is open the file in read mode. #include int main() { FILE * file; file = fopen("BCA.txt","r"); } Writing Data to a File Let's write in the file that we created in the previous example. So to do that using fprintf() to write a text in the file with the name BCA.txt. #include int main(){ FILE *file; file = fopen("BCA.txt", "w"); fprintf(file, "Hello! Welcome to BCA SEM-2 MJCC.\n"); } Reading Data from an Existing File To read data from an existing file we will use “r” mode in file opening. To read the file character by character we use getc() and to read line by line we use fgets(). 5 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators #include #include int main() { FILE *fp; char s; fp=fopen("BCA.txt","r"); if(fp==NULL) { printf("\nCAN NOT OPEN FILE"); exit(1); } do { s=getc(fp); // read file character by character printf("%c",s); } while(s!=EOF); fclose(fp); return 0; } Moving Data to a Specific Location on the File To put the file pointer to a specific place we use fseek(). With the help of it we can write data at whatever location we want in the file. 6 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators The function fseek() is a standard library function in C language, present in stdio.h header file. It is used to move or change the position of the file pointer which is being used to read the file, to a specified offset position. Syntax of fseek() in C fseek(FILE *filePointer, long offset, int origin); The function fseek in c receives three parameters filePointer : pointer to the FILE object that identifies the stream, which we have to modify. offset : number of bytes to shift the position of the FILE pointer, relative to its current origin to determine the new position. origin : determines the current position of the FILE pointer from where the offset needs to be added ie. it indicates the contemporary position of the file pointer from where the specified offset value will be added, in order to move the position of the file pointer using the fseek() function. The parameter origin can have the following three values SEEK_END : denotes the end of the file SEE_SET : denotes the starting of the file SEEK_CUR : denotes the current position of the file pointer. // C Program to demonstrate the use of fseek() #include void main() { FILE *fp; fp = fopen("test.txt", "r"); 7 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators // Moving pointer to end fseek(fp, 0, SEEK_END); // Printing position of pointer printf("%ld", ftell(fp)); getch(); } The file test.txt contains the following text: fwrite and fread For writing in file, it is easy to write string or integer to file using fprintf and putc, but you might have faced difficulty when writing contents of data means that structure. fwrite and fread make task easier when you want to write and read blocks of data. fwrite : Following is the declaration of fwrite function size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) ptr - This is pointer to 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, each one with a size of size bytes 8 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators stream - This is the pointer to a FILE object that specifies an output stream fread : Following is the declaration of fread function 9 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators 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. 10 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Closing the File To close a file which is already open, we will use fclose(). #include int main(){ FILE *file; file = fopen("BCA.txt", "w"); fprintf(file, "Hello! Welcome to BCA SEM-2 MJCC.\n"); fclose(file); } In this example, the file is the pointer associated with the file(BCA.txt) which is to be closed. After closing the file the file pointer lost the reference of the file and start pointing to NULL. 11 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Pre-Processor As the name suggests, Pre-processors are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C. Pre-processor programs provide pre-processor directives that tell the compiler to pre-process the source code before compiling. All of these pre- processor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the pre-processor program to get executed. Examples of some pre-processor directives are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include extra code in your program. We can place these preprocessor directives anywhere in our program. important preprocessor directives − Sr.No. Directive & Description 1 #define Substitutes a preprocessor macro. 2 #include Inserts a particular header from another file. 3 #undef Undefines a preprocessor macro. 4 #ifdef Returns true if this macro is defined. 12 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators 5 #ifndef Returns true if this macro is not defined. 6 #if Tests if a compile time condition is true. 7 #else The alternative for #if. 8 #elif #else and #if in one statement. 9 #endif Ends preprocessor conditional. 10 #error Prints error message on stderr. 11 #pragma Issues special commands to the compiler, using a standardized method. Macros Macro in C programming is known as the piece of code defined with the help of the #define directive. Macros in C are very useful at multiple places to replace the piece of code with a single value of the macro. Macros have multiple types and there are some predefined macros as well. Suppose we are working on an application in C language and there is one value or an object or segment of code which we require so many times in our code then with the help of macros we can define it once and use it many times. Macros are one of the convenient ways to write robust and scalable code. The syntax of the macro is as shown in the following figure. Here, we will have the three components: 13 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators 1. #define - Preprocessor Directive 2. PI - Macro Name 3. 3.14 - Macro Value #include // This is macro definition #define PI 3.14 void main() { // declaration and initialization of radius int radius = 5; // declaration and calculating the area float area = PI * (radius*radius); // Printing the area of circle printf("Area of circle is %f", area); } Bitwise Operators in C Bitwise operators are used to manipulate bits in various different ways. They are equivalent to how we use mathematical operations like (+, -, /, *) among numbers, similarly we use bitwise operators like (|, &, ^, , ~) among bits. 14 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Bitwise operators in C There are 6 bitwise operators in total in the C language. They are  AND (&)  OR (|)  XOR (^)  COMPLEMENT (~)  Left Shift () The symbols and names of some of these operators may appear similar to the logical operators, But make no mistake, these are different from them. AND (&) The bitwise AND operator is denoted using a single ampersand symbol, i.e. &. This is a binary operator; it needs two operands -- two integers -- to work on. It takes the binary values of both the left and right operands and performs the logical AND operation over them on the bit level, i.e. if both the operands have 1 on the specified position then the result will also have 1 in the corresponding position or else there will be 0. Num1 Num2 Result=Num1 & Num2 0 0 0 1 0 0 0 1 0 1 1 1 int ans, num1 = 3, num2 = 4; ans = num1 & num2; printf("3 & 4 = %d", ans); Output: 3&4=0 15 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators Notes:  The above code snippet performs the bitwise AND operation on 3 and 4. Let’s see their working in detail.  The binary value for 3 is 11 and 4 is 100.  First, we have to convert the shortest binary value to the length of the longest one, by adding zeros to the left side - the most significant bit.  Here the number with the shortest length is 3, with lengths 2 and the largest one is 4 with length 3. Convert them to the same length by adding 0s as the most significant bit in 3.  So, now we have 011 as binary representations for 3 and 100 for 4.  Now move from left to right, and perform logical AND operations on the bits and store the result in the corresponding position.  The first bit of 3 is 0 and the first bit of 4 is 1, the logical AND will consider 0 as False and 1 as True, so the result will be false and 0 will be the first bit of the result.  The same process repeats itself throughout the length of the binary values. The second bit of 3 and 4 are 0 and 0 respectively, so again 0 will be stored as the second bit of the result.  The third and last bit of both 3 and 4 are 0 and 0, so again 0 will be the third and final bit of our result.  So the final binary value of our result will be 000, which when converted to integer decimal results to 0. OR The bitwise OR operator is much similar to the bitwise AND, the only difference is that the bitwise OR operator performs logical OR instead of logical AND on the bit level, i.e. if at least any one of the operands have 1, then the result will also have 1 in the corresponding position, and 0 if they both 16 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators have 0 in the corresponding position.This is denoted using the vertical bar or pipe symbol, i.e. |. Num1 Num2 Result=Num1 | Num2 0 0 0 1 0 1 0 1 1 1 1 1 Truth table for Bitwise OR operator in C Code int ans, num1 = 3, num2 = 4; ans = num1 | num2; printf("3 | 4 = %d", ans); Output: 3|4=7 Working  The above code snippet performs the bitwise OR operation on 3 and 4. Let’s see their working in detail.  The binary value for 3 is 11 and 4 is 100.  First, we have to convert the shortest binary value to the length of the longest one, by adding zeros to the left side - the most significant bit.  So, now we have 011 for 3 and 100 for 4.  Now move from left to right, and perform logical OR operations on the bits and store the result in the corresponding position  The first bit of both 3 and 4 are 0 and 1, respectively, so the first bit of the result is 1. 17 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators  The second bit of both 3 and 4 are 1 and 0, respectively, so the second bit of the result is also 1.  The third bit of both 3 and 4 are 1 and 0, respectively, so the third bit of the result is also 1.  So the binary value of the result is 111, which when you convert from binary to decimal returns 7. XOR This is similar to the other two, but the only difference is that they perform logical XOR on the bit level, i.e., if exactly one of the operands has 1 and the other has 0 then the result will have 1 in the corresponding position, and 0 if they have the same bits such as both 0s or both 1s. Num1 Num2 Result=Num1^Num2 0 0 0 1 0 1 0 1 1 1 1 0 Truth table for Bitwise XOR operator in C Let’s continue with the same example that we used for the previous two operators. Code int ans, num1 = 3, num2 = 4; ans = num1 ^ num2; printf("3 ^ 4 = %d", ans); Output: 3|4=7 18 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators COMPLEMENT We have seen three bitwise so far, if you have noticed, all of them were binary operators, i.e. they all require two operands to perform their functions. But this one is different, this is the only bitwise operator that requires only one operand. All other bitwise operators require 2 operators. The bitwise complement operator takes a single value and returns the one’s complement of the value. The one’s complement of a number is obtained by changing all the 0’s in its binary value to 1’s and by changing the 1’s to 0’s. It is denoted using the tilde symbol, i.e. ‘~’. Num1 Result = ~Num1 0 1 1 0 Truth table for Bitwise Complement operator in C Code int ans, num1 = 5; ans = ~num1; printf("~5 = %d", ans); Output ~5 = 6 Shift Left The shift left operator shifts the bit pattern of an integer value by a specified number of bits to the left. 19 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators The Shift Left operator takes two operands, a value on which the shift operation is to be performed, say ‘x’, and another value that specifies the number of bit positions that have to be shifted on the fore mentioned value, say ‘n’. The value of ‘x’ can be negative, but not that of ‘n’, if the value of ‘n’ is negative then the compiler will throw an error, saying ‘negative shift count’ When the value of 'x' is negative, the Left Shift operation is performed on the two’s complement of the number. So there is a possibility that the sign of the number may or may not be the same as the left shift operation. The Shift Left operator is denoted using two consecutive greater than operators, i.e. > 2 = 5 21 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval B.C.A SEM-2 UNIT-3 File Management, Pre-processors and Bit-wise operators  Note:  The above code snippet performs the Shift Right operation on the decimal value 20.  It shifts the bit patterns of 20 by 2  The binary value for 20 is 10100.  When you shift it to the right by 2 positions, i.e. Pop the last 2 bits, the result that you get is 101.  The result when converted from binary to integer produces 5 22 M.J.COLLEGE OF COMMERCE Prepared By: - Kalyani Raval