0% found this document useful (0 votes)
14 views27 pages

FileHandling_2

The document provides an overview of file handling in C, focusing on binary files and random access files, including functions like fwrite(), fread(), fseek(), and their usage. It also discusses preprocessor directives, command-line arguments, and how to handle them in C programs. Key concepts such as macros, file inclusion, and conditional compilation are explained with examples.

Uploaded by

mnsk9632
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views27 pages

FileHandling_2

The document provides an overview of file handling in C, focusing on binary files and random access files, including functions like fwrite(), fread(), fseek(), and their usage. It also discusses preprocessor directives, command-line arguments, and how to handle them in C programs. Key concepts such as macros, file inclusion, and conditional compilation are explained with examples.

Uploaded by

mnsk9632
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit IV

File Handling 2
Unformatted files(Binary files)
• A binary file is a computer file that stores data using a binary encoding scheme, composed of
sequences of 0s and 1s. Unlike text files, which use characters to be data, binary files directly
encode information into binary format.
• The fwrite() function is used to write records or sequence of bytes or we can say binary data to
the file. A record which we are writing may be an array or a structure.
• The fread() function is used to read bytes or binary data from the file.
main.c

Output when main.c is executed


Random Access file
• Random access file in C enables us to read or write any data in our disk file without reading or
writing every piece of data before it.

• In a random-access file, we may quickly search for data, edit it or even remove it.

• We can open and close random access files in C, same as sequential files with the same opening
mode, but we need a few new functions to access files randomly.

• This extra effort pays off flexibility, power, and disk access speed.

• Random access to a file in C is carried with the help of functions like ftell(), fseek() and rewind().
• Random access to a file can be employed in this situation, enabling access to any record at any
point in the file.
• Example::We can imagine data in a random access file as songs on a compact disc or record; we
can fast forward directly to any song we want without playing the other pieces. We can do so if
we're playing the first song, the sixth song, the fourth song. This order has nothing to do with the
songs' order initially recorded.
• Random file access sometimes takes more programming but rewards our effort with a more
flexible file-access method.
fseek()
• The fseek() function moves the file position to the desired location.
• Its syntax is:
int fseek(FILE *fp, long displacement, int origin);
• The various components are as follows:
• fp – file pointer.
• displacement - represents the number of bytes skipped backwards or forwards
from the third argument's location. It's a long integer that can be either positive
or negative.
• origin – It's the location relative to the displacement.
It accepts one of the three values listed below.

Constant Value Position


SEEK_SET 0 Beginning of file
SEEK_CURRENT 1 Current position
SEEK_END 2 End of file

Here is the list of common operations that we can perform using the fseek() function

Operation Description
fseek(fp, 0, 0) This takes us to the beginning of the file.
fseek(fp, 0, 2) This takes us to the end of the file.
fseek(fp, N, 0) This takes us to (N + 1)th bytes in the file.
fseek(fp, N, 1) This takes us N bytes forward from the current position in the file.

fseek(fp, -N, 1) This takes us N bytes backward from the current position in the file.
Example:
Example
Files holding data

Screen visible data


Debugging
Debugging
C-Preprocessor
• Preprocessors are programs that process the source code before compilation. Several
steps are involved between writing a program and executing a program in C
• The preprocessor statements in C are called directives. A preprocessor section of the
program always appears at the top of the C code. Each preprocessor statement starts
with the hash (#) symbol.
Preprocessor Directives in C
The following table lists down all the important preprocessor directives −
Directive Description
• # define Substitutes a preprocessor macro.--------------------------------------MACRO
• #include Inserts a particular header from another file.------------------------FILE INCLUSION
• #ifdef Returns true if this macro is defined.
• #ifndef Returns true if this macro is not defined.
• #if Tests if a compile time condition is true.
• #else The alternative for #if. ----CONDITIONAL
COMPILATION
• #elif #else and #if in one statement.
• #endif Ends preprocessor conditional.
• #error Prints error message on stderr.
• #pragma Issues special commands to the compiler,
using a standardized method. ---------OTHER DIRECTIVES
• #undef Undefines a preprocessor macro.
• Macro::In C, 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(;).

• File inclusion::File inclusion in C is a method that allows the contents of one file to be
inserted into another file. This is done using the #include preprocessor directive, which
tells the preprocessor to insert the contents of the specified file into the current file.

• Conditional Compilation:: It is a set of preprocessing directives that allows us to exclude


and include parts of a program based on specified conditions. Each directive in the
compilation is processed across different platforms, including debug and release
versions.

• Other directives::Apart from the above directives, there are two more directives that are
not commonly used.
Example-macro and file inclusion
Example: chain of macros
Predefined macros
Example
Example #if #endif #error--C Conditional compilation
#include <stdio.h>
/tmp/OJOLy4pHqO/main.c: In function 'main':
#include <limits.h> ERROR!
/tmp/OJOLy4pHqO/main.c:12:10: error: #error Integer size cannot hold
#define MILLISECONDS(age) (age * 365* 24 * 60 * 60 * 1000 ) our age in milliseconds
12 | #error Integer size cannot hold our age in milliseconds
int main() | ^~~~~
/tmp/OJOLy4pHqO/main.c:4:52: warning: integer overflow in expression
{ of type 'int' results in '474877952' [-Woverflow]
4 | #define MILLISECONDS(age) (age * 365* 24 * 60 * 60 * 1000 )
/* The age of TechOnTheNet in milliseconds */ | ^
/tmp/OJOLy4pHqO/main.c:17:10: note: in expansion of macro
int age; 'MILLISECONDS'
17 | age = MILLISECONDS(12);
| ^~~~~~~~~~~~
#if INT_MAX < MILLISECONDS(12)
#error Integer size cannot hold our age in milliseconds
#endif
/* Calculate the number of milliseconds in 12 years */
age = MILLISECONDS(12);
printf("TechOnTheNet is %d milliseconds old\n", age);
return 0;
}
Other directives::Example
#include <stdio.h>
// defining MIN_VALUE
#define MIN_VALUE 10
int main() {
// Undefining and redefining MIN_VALUE
printf("Min value is: %d\n",MIN_VALUE);
//undefining max value
#undef MIN_VALUE
// again redefining MIN_VALUE
#define MIN_VALUE 20
printf("Min value after undef and again redefining it: %d\n", MIN_VALUE);
return 0;
}
Command Line Arguments
• The most important function of C is the main() function. It is mostly
defined with a return type of int and without parameters.
• int main() {
...
}
• We can also give command-line arguments in C. Command-line
arguments are the values given after the name of the program in the
command-line shell of Operating Systems. Command-line arguments
are handled by the main() function of a C program.
• To pass command-line arguments, we typically define main() with two arguments: the first
argument is the number of command-line arguments and the second is a list of command-
line arguments.
• Syntax
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program. So if we pass a value to a
program, the value of argc would be 2 (one for argument and one for program name).The value
of argc should be non-negative.
• argv (ARGument Vector) is an array of character pointers listing all the arguments.
• If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
• argv[0] is the name of the program , After that till argv[argc-1] every element is command -
line arguments.
#include <stdio.h>
#include <stdlib.h> cc cla_p1_sum.c
int main(int argc, char *argv[]) { ./a.out 1 2 3
The sum of 1, 2, and 3 is: 6
// Check if exactly 3 arguments are passed
if (argc != 4) {
printf("No of arguments does not match");
return 1;
}
// Convert command line arguments to integers
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
int num3 = atoi(argv[3]);
// Perform the sum
int sum = num1 + num2 + num3;
// Display the result
printf("The sum of %d, %d, and %d is: %d\n", num1, num2, num3, sum);
return 0;
#include <stdio.h>
#include <stdlib.h>
cc cla_p2.c
int main(int argc, char *argv[]) { ./a.out a.c
if (argc != 2) { Hello hi
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print each character to the console
}
fclose(file);
return 0;
}

You might also like