FileHandling_2
FileHandling_2
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
• 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.
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
• 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.
• 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;
}