Module 5 Files, Macros

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

A File can be used to store a large volume of persistent data.

information is stored on the memory device in the form of a datafile.

Data files allow us to store information permanently, and to access and alter that
information whenever necessary.

there are two different types of data files,

● Steam-oriented (or standard) data files,


● System-oriented (or low-ZeveZ)data files
Stream-oriented data files can be subdivided into two categories,
In the first category are text files, consisting of consecutive characters.
These characters can be interpreted as individual data items, or as components
of strings or numbers.
The second category of stream-oriented data files are…
unformatted data files, organizes data into blocks containing contiguous bytes
of information.
These blocks represent more complex data structures, such as arrays and
structures.
A separate set of library functions is available for processing stream oriented data
files of this type.
OPENING AND CLOSING A DATA FILE
When working with a stream-oriented data file, the first step is to establish a bufler
area, where information is temporarily stored while being transferred between the
computer’s memory and the data file
This buffer area allows information to be read from or written to the data file
The buffer area is established by writing :
FILE *ptvar;
where FILE (uppercase letters required) is a special structure type
that establishes the buffer area, and ptvar is a pointer variable that indicates the
beginning of the buffer area.
A data file must be opened before it can be created or processed.
ptvar = fopen( file-name, file-type);

a data file must be closed at the end of the program


f close (ptvar);
C compilers will automatically close a data file at the end of program execution if a
call to fclose is not present.
The first statement causes the header file stdio .h to be included in the program

The second statement defines a pointer called fpt which will point to a structure of
type FILE. indicating the beginning of the data-file buffer area.

The third statement opens a new data file called sample. dat as a write-only file

fpt points to the buffer area associated with the data file sample. Dat

the last statement closes the data file.


int main() {
FILE *fptr;

// Create a file on your computer (filename.txt)


fptr = fopen("filename.txt", "w");

// Close the file


fclose(fptr);

return 0;
}
to create the file in a specific folder, just provide an absolute path:

fptr = fopen("C:\directoryname\filename.txt", "w");


UNFORMATTED DATA FILES
Some applications use the data files to store blocks of data, where each block consists
of a fixed number of contiguous bytes.
Each block will generally represent a complex data structure, such as a structure or an
array.
a data file may consist of multiple structures having the same composition, or it may
contain multiple arrays of the same type and size.
For such applications it may be desirable to read the entire block from the data file, or
write the entire block to the data file, rather than reading or writing the individual
components (i.e., structure members or array elements) within each block separately.
Unformatted I/O refers to a category of I/O operations that reads or writes data as a
stream of bytes without regard to any format. Unformatted I/O in C is carried out with
the aid of functions like fread() and fwrite(). Without formatting, these operations are
used to read and write data directly to and from files.

count is the number of elements to be written, size is the size of each element to be
written, and the file pointer is a pointer to the file where the data will be written.
Syntax for using the fread() method with unformatted input:

fread(data, size, count, file pointer);

a pointer to the buffer where the data will be read, the size of each element to be
read, the number of elements to be read, and a pointer to the file from which the
data will be read.
The library functions fread and fwrite are intended to be used in situations of this
type.

These functions are often referred to as unformatted read and write functions.
Similarly, data files of this type are often referred to as unformatted data files.

fwrite(&customer, sizeof(record), 1, fpt);

where customer is a structure variable of type record, and fpt is the stream pointer
associated with a data file that has been opened for output
Concept of Binary File

A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters.
They contain data that is stored in a similar manner to how it is stored in the main
memory.
● The binary files can be created only from within a program and their contents
can only be read by a program.
● More secure as they are not easily readable.
● They are generally stored with .bin file extension.
All machine language files are binary files.
For opening a binary files, filemode has to be mentioned as “rb” or “wb” in fopen
command.
b stands for binary(files)
Binary files differ from text files in two ways:
The storage of new line characters
The eof character
Differences between Text and Binary file

■ A text file stores data in the form of alphabets, digits and other special symbols by
storing their ASCII values and are in a human readable format. For example, any file
with a .txt, .c, etc extension. Whereas, a binary file contains a sequence or a
collection of bytes which are not in a human readable format. For example, files with
.exe, .mp3, etc extension. It represents custom data.
■ A small error in a textual file can be recognized and eliminated when seen.
Whereas, a small error in a binary file corrupts the file and is not easy to detect.
■ Since the data is not human readable it also adds to the security of the content as
one might not be able to get data if the structure is not known.
■ Now, when it comes to programming the major differences between the two, are.,
Handling of newlines, representation of EOF(End of File).
text mode and the binary mode can be distinguished is on the basis of the
representation of the end-of-file(EOF). In the text mode, a special character with the
ASCII code 26 is inserted at the end of the file. This character when encountered
returns the EOF signal to the program.

This is not the case in binary mode. In the binary mode, we do not have any special
character to signify the EOF. It keeps track with the help of the number of characters
present in the directory entry of the file.
Opening a binary file
To open a file in binary mode, use the rb, rb+, ab, ab+, wb, and wb+ access
mode in the fopen() function. Also use the .bin file extension in the binary
filename.
Example
fptr = fopen("filename.bin", "rb");
Write to a Binary File

Use fwrite() function to write data to a binary file. The data is written to the binary file in the from of bits
(0’s and 1’s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
Parameters:
● ptr: pointer to the block of memory to be written.
● size: size of each element to be written (in bytes).
● nmemb: number of elements.
● file_pointer: FILE pointer to the output file stream.
// C program to write to a Binary file using fwrite()
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
// Structure variable declared here.
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("C:\\program.bin", "wb")) == NULL) {
printf("Error! opening file");
// If file pointer will return NULL
// Program will exit.
exit(1);
}
int flag = 0;
// else it will return a pointer to the file.
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
flag = fwrite(&num, sizeof(struct threeNum), 1,
fptr);
}

// checking if the data is written


if (!flag) {
printf("Write Operation Failure");
}
else {
printf("Write Operation Successful");
}

fclose(fptr);

return 0;
}
REGISTER VARIABLES
Registers are special storage areas within the computer’s central processing unit.

The actual arithmetic and logical operations that comprise a program are carried
out within these registers.

Normally, these operations are carried out by transferring information from the
computer’s memory to these registers, carrying out the indicated operations, and
then transferring the results back to the computer’s memory.

The execution time can be reduced considerably if certain values can be stored
within these registers rather than in the computer’s memory.

Such programs may also be somewhat smaller in size (i.e., they may require
fewer instructions), since fewer data transfers will be required.
In C, the values of register variables are stored within the registers of the central
processing unit.
A variable can be assigned this storage class simply by preceding the type
declaration with the keyword register.
register int a, b, c;
This declaration specifies that the variables a, b and c will be integer variables with
storage class register.
Hence, the values of a, b and c will be stored within the registers of the computer’s
central processing unit rather than in memory, provided the register space is
available.
If the register space is not available, then the variables will be treated as integer
variables with storage class automatic. This is equivalent to the declaration auto
int a, b, c;
C program to implement register variable
#include <stdio.h>
int main() {
register char x = 'B';
register int a = 20;
register short b = 35;
printf("The value of register variable x : %c\n",x);
printf("The value of register variable a : %d\n",a);
printf("The value of register variable b : %d\n",b);
return 0;
}
BITWISE OPERATIONS
Some applications require the manipulation of individual bits within a word of
memory.

Assembly language or machine language is normally required for operations of


this type

C contains several special operators that allow such bitwise operations to be


carried out easily and efficiently.

These bitwise operators can be divided into three general categories: the one’s
complement operator, the logical bitwise operators, and the shift operators.
The One’s Complement Operator
The one’s complement operator (-) is a unary operator that causes the bits of its
operand to be inverted (i.e., reversed), so that 1s become OS and OS become 1s.
The operand must be an integer-type quantity (including integer, long, short,
unsigned, char, etc.).
Consider the hexadecimal number 07ff. The corresponding bit pattern, expressed
in terms of a 16-bit word, is 0000 01 11 11 11 11 11 .
The one’s complement of this bit pattern is 11 11 1000 0000 0000, which
corresponds to the hexadecimal number f8OO.
Thus, the value of the expression - 07ff is f800.
The Logical Bitwise Operators

● bitwise and (a)


● bitwise exclusive or (A)
● bitwise or ( I )
Each of these operators requires two integer-type operands.

the least significant bits (i.e., the rightmost bits) within the two operands will
be compared, then the next least significant bits, and so on, until all of the bits
have been compared.
A bitwise and expression will return a 1 if both bits have a value of 1 (i.e.,
if both bits are true). Otherwise, it will return a value of 0.
A bitwise exclusive or expression will return a 1 if one of the bits has a
value of 1 and the other has a value of 0 (one bit is true, the other false.
Otherwise, it will return a value of 0.
A bitwise or expression will return a 1 if one or more of the bits have a
value of 1 (one or both bits are true). Otherwise, it will return a value of 0.
Masking

Masking is a process in which a given bit pattern is transformed


into another bit pattern by means of a logical bitwise operation. The
original bit pattern is one of the operands in the bitwise operation.
The second operand, called the mask, is a specially selected bit
pattern that brings about the desired transformation.
ENUMERATIONS
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the
names make a program easy to read and maintain.

Enum tag { member 1,member 2, member 3…… member m}


Enumeration constants are automatically assignment equivalent integer values, beginning
with 0 for the first constant with each successive constant increasing by 1.
Member 1 will automatically be assigned the value 0 , member 2 will be assignemed 1
and so on
#include <stdio.h>

enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
MACROs

A macro is a piece of code in a program that is replaced by the value of the


macro.
Macro is defined by #define directive.
Whenever a macro name is encountered by the compiler, it replaces the
name with the definition of the macro.
Macro definitions need not be terminated by a semi-colon(;).
// C program to illustrate macros
#include <stdio.h>

// Function-like Macro definition


#define area length * width

// Driver Code
int main()
{

// Given two number a and b


int length,width;

printf("length =" );
scanf("%d",&length);
printf("width =" );
scanf("%d",&width);
printf("\n area = %d",area);
return 0;
}
#include <stdio.h>
#define ADD(x,y) x+y
int main()
{
printf("%d", ADD(3,2));
return 0;
}

You might also like