File Handelling in C
File Handelling in C
In programming, we may require some specific input data to be generated several numbers
of times. Sometimes, it is not enough to only display the data on the console. The data to
be displayed may be very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store it onto the
local file system which is volatile and can be accessed every time. Here, comes the need of
file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.
o The file name (string). If the file is stored at some specific location, then we must mention the
path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
Mode Description
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character
file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. } Output:
Hello file by fprintf...
1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. } Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin directory,
you will see emp.txt file. It will have following information.
emp.txt
Id= 1
Name= sonoo
Salary= 120000
Syntax:
1. int fputc(int c, FILE *stream)
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
myfile.txt
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }
Output:
hello c programming
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write
data into file at desired location.
Syntax:
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is My Program", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
File*: The FILE *stream argument is a reference to the file's associated FILE structure. By
utilizing the fopen() method, it is acquired.
Long int offset: The offset parameter specifies how many bytes will relocated to the whence
parameter's location. It may be zero, positive, or negative.
Whence is an integer that indicates the reference place from which the offset is determined.
Any one of the following three constants may be used:
The file pointer is being moved: You can shift the file pointer to a specified area of the file
using the fseek() method. You can change the reference point for the offset by altering
the 'whence' parameter to one of the values SEEK_SET, SEEK_CUR, or SEEK_END.
Putting Data in the Right Place: Using operations like fprintf(), fputs(), fwrite(), etc., you
may write data after shifting the file reference to the correct spot. The data will be written
beginning at the file pointer's new location.
A file position indicator update: The fseek() method automatically updates the file
position indication to reflect the changed location of the file pointer. By doing this, you may
be confident that the file will always be operated on from the right angle.
Random Access: The fseek() function allows you random access to a file, enabling you
to read or write data at any point you want inside the file. It is especially beneficial for huge
files or databases when sequential data access is not the most effective method.
Modifying Existing Data: Without rewriting the whole file, fseek() lets you edit data at
specified locations inside a file. You can replace or insert new data while keeping the
present contents by shifting the file pointer to the appropriate spot.
Data Appending: You may relocate the file pointer to the end of the file and add additional
data by using the fseek() function with the SEEK_END constant. It is quite helpful when
working with log files or adding entries to an existing file.
Reading Specific Portions: You can read only the information you need by using
the fseek() function to move to a specific location inside a file. Working with huge files or
structured data can improve file reading procedures.
Support for huge Files: The fseek() function is compatible with huge files when given
a file offset of type long int. You may now work with files that are larger than what is
allowed by standard file operations.
Considerations for Performance: Although fseek() function offers flexibility, frequent use
of random-access operations can have an adverse effect on speed, particularly with big files.
Consider the trade-off between convenience and performance when considering whether
to use fseek() for file manipulation.
Here are several examples of how to use the C fseek() function and their accompanying
results:
Example 1:
Consider the following text in a file called "data.txt":
1. Line 1
2. Line 2
3. Line 3
4. Line 4
5. Line 5
Code:
1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("data.txt", "r");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. char line[100];
11. fseek(file, 4, SEEK_SET); // Move to the beginning of the fourth line
12. fgets(line, sizeof(line), file);
13. printf("Fourth line: %s", line);
14.
15. fclose(file);
16. return 0;
17. }
Output:
Fourth line: Line 4
Example 2:
Let's say we have a binary file called "data.bin" that contains the following information:
1. 1 2 3 4 5
Code:
1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("data.bin", "r+b");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9. int value = 10;
10. fseek(file, 3 * sizeof(int), SEEK_SET); // Move to the fourth integer (zero-based index)
11. fwrite(&value, sizeof(int), 1, file);
12. fclose(file);
13. return 0;
14. } Output:
File contents after writing: 1 2 3 10 5
Example 3:
Consider the following text in a file called "log.txt":
1. Log entry 1
2. Log entry 2
Code:
1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("log.txt", "a");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. fseek(file, 0, SEEK_END); // Move to the end of the file
11. fputs("\nLog entry 3", file);
12.
13. fclose(file);
14. return 0;
15. }
Output:
Log entry 1
Log entry 2
Log entry 3
Example 4:
1. #include <stdio.h>
2. int main() {
3. FILE *file = fopen("data.txt", "r");
4. if (file == NULL) {
5. printf("Unable to open the file.\n");
6. return 1;
7. }
8. fseek(file, 0, SEEK_END); // Move to the end of the file
9. long size = ftell(file); // Get the file size
10. printf("File size: %ld bytes\n", size);
11.
12. fclose(file);
13. return 0;
14. }
Output:
The fseek() function in the C laguage allows programmers to set the file pointer to a given
offset inside a file, making it an essential tool for file manipulation. Developers may
perform various tasks, including random access, adding data, editing existing
material, and reading particular file sections, skillfully utilizing the fseek() function.
For fseek() to operate properly, it is crucial to comprehend its syntax, which comprises
the FILE pointer, offset, and whence arguments. The reference location from which the
offset is computed is determined by the three variables SEEK_SET, SEEK_CUR,
and SEEK_END, enabling precise control over the movement of the file pointer.
Programmers may manage big files, access data structures in binary files, and modify
metadata sections with the help of fseek(). Additionally, the function has error-handling
features that make it possible to identify and fix problems like looking outside of file
boundaries or using closed files.
When using fseek(), it's crucial to consider the compromise between ease and speed.
Performance can be impacted by excessive random-access operations, especially when
dealing with big files. Therefore, it is essential to analyze how to optimize file handling and
reduce pointless carefully seeks.
Developers may improve their ability to manipulate files by understanding the fseek()
method, which will make their programs more effective, adaptable, and resilient.
Programmers can easily handle sophisticated file operations due to fseek(), which enables
file navigation, data modification, and content adding.
fseek() is a useful tool for manipulating file pointers and accessing data at precise points in
the world of file management in C. By embracing and comprehending the potential of
fseek(), developers may handle files with a new degree of precision and control, resulting in
more complex and useful programs.
C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.
C Macros
C macros provide a potent method for code reuse and simplification. They let programmers
construct symbolic names or phrases that are changed to certain values before the
compilation process begins. The use of more macros makes code easier to comprehend,
maintain, and makes mistakes less likely. In this article, we'll delve deeper into the concept
of C macros and cover their advantages, ideal usage scenarios, and potential hazards.
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
1. #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros
The function-like macro looks like function call. For example:
Visit #define to see the full example of object-like and function-like macros.
C Predefined Macros
ANSI C defines many predefined macros that can be used in c program.
1. #include<stdio.h>
2. int main(){
3. printf("File :%s\n", __FILE__ );
4. printf("Date :%s\n", __DATE__ );
5. printf("Time :%s\n", __TIME__ );
6. printf("Line :%d\n", __LINE__ );
7. printf("STDC :%d\n", __STDC__ );
8. return 0;
9. }
Output:
File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1
Code reuse: By allowing developers to declare a piece of code just once and use it several
times, macros help to promote modular programming and minimize code duplication.
Code abbreviation: Macros make it possible to write clear, expressive code that is simpler
to read and comprehend the intentions of the programmer.
Macro Side consequences: Steer clear of macros with negative consequences. Multiple
evaluations of macro arguments may result in surprising results since macros are directly
substituted.
Use capital letters to distinguish macro names from standard C identifiers and to make the
code easier to understand.
For object-like macros, use constants: If possible, use object-like macros for constants to
make the code more readable and make any necessary adjustments simpler.
Macros with Functions for Basic Operations: Use macros that resemble functions for
straightforward, one-line operations. Use normal functions in their place for more intricate
processes.
Use Predefined Macros Wisely: While predefined macros like __DATE__, __TIME__, and
__FILE__ are useful for debugging and logging, don't rely on them for essential functions.
Conclusion:
As a result, C macros are a crucial component of the C programming language and give
programmers a strong tool for code reuse and optimization. Object-like macros act
as symbolic constants and improve code readability by giving numerical values names that
make sense. The cost of function calls has decreased, and efficiency is increased through
function-like macros, which operate as in lined code snippets.
Code reuse, code simplification, and conditional compilation are a few advantages of
using macros in C. Programmers can build modular code structures and streamline
complicated procedures by designing macros. Additionally, conditional
compilation facilitates platform-specific functions and debugging by enabling developers
to include or remove code blocks based on certain criteria.
To support command line argument, you need to change the structure of main() function as
given below.
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name
always.
Example
Let's see the example of command line arguments where we are passing one argument with
file name.
1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %s\n", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.\n");
8. }
9. else{
10. printf("First argument is: %s\n", argv[1]);
11. }
12. }
1. ./program hello
Output:
Output:
But if you pass many arguments within double quote, all arguments will be treated as a
single argument only.
Output:
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.
Features of C Language
Answer: A good programming language it must have the following characteristics:
Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
inputs. It may or may not take input. Well-Defined Outputs: The algorithm must clearly
define what output will be yielded and it should be well-defined as well. It should produce
at least 1 output. Finite-ness: The algorithm must be finite, i. it should terminate after a finite
time.
Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
must be just plain instructions that can be implemented in any language, and yet the
Ans:
Pseudo code: It’s simply an implementation of an algorithm in the form of annotations and informative
text written in plain English. It is a methodology that allows the programmer to represent the
implementation of an algorithm. It has no syntax like any of the programming language and thus can’t be
compiled or interpreted by the computer. Kernel is central component of an operating system that
manages operations of computer and hardware. It basically manages operations of memory and CPU time.
It is core component of an operating system. Kernel acts as a bridge between applications and data
processing performed at hardware level using inter-process communication and system calls
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
5. system("cls");
6. printf("enter the number of row=");
7. scanf("%d",&r);
8. printf("enter the number of column=");
9. scanf("%d",&c);
10. printf("enter the first matrix element=\n");
11. for(i=0;i<r;i++)
12. {
13. for(j=0;j<c;j++)
14. {
15. scanf("%d",&a[i][j]);
16. }
17. }
18. printf("enter the second matrix element=\n");
19. for(i=0;i<r;i++)
20. {
21. for(j=0;j<c;j++)
22. {
23. scanf("%d",&b[i][j]);
24. }
25. }
26.
27. printf("multiply of the matrix=\n");
28. for(i=0;i<r;i++)
29. {
30. for(j=0;j<c;j++)
31. {
32. mul[i][j]=0;
33. for(k=0;k<c;k++)
34. {
35. mul[i][j]+=a[i][k]*b[k][j];
36. }
37. }
38. }
39. //for printing result
40. for(i=0;i<r;i++)
41. {
42. for(j=0;j<c;j++)
43. {
44. printf("%d\t",mul[i][j]);
45. }
46. printf("\n");
47. }
48. return 0;
49. }
Qus: Write a program in C to print the following pattern:
12345
1234
123
12
1
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Selection Sort Algorithm
In this article, we will discuss the Selection sort Algorithm. The working procedure of selection sort
is also simple. This article will be very helpful and interesting to students as they might face
selection sort as a question in their examinations. So, it is important to discuss the topic.
In selection sort, the smallest value among the unsorted elements of the array is selected in every
pass and inserted to its appropriate position into the array. It is also the simplest algorithm. It is an
in-place comparison sorting algorithm. In this algorithm, the array is divided into two parts, first is
sorted part, and another one is the unsorted part. Initially, the sorted part of the array is empty, and
unsorted part is the given array. Sorted part is placed at the left, while the unsorted part is placed at
the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the first
position. After that second smallest element is selected and placed in the second position. The
process continues until the array is entirely sorted.
The average and worst-case complexity of selection sort is O(n2), where n is the number of items.
Due to this, it is not suitable for large data sets.
#include <stdio.h>
void selection(int arr[], int n)
{ int i, j, small;
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array
for (j = i+1; j < n; j++)
if (arr[j] < arr[small])
small = j;
// Swap the minimum element with the first element
int temp = arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}
void printArr(int a[], int n) /* function to print the array */
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
selection(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}