You are on page 1of 27

File handling in C

• A file is a collection of data stored on a secondary storage device like


hard disk.
• A file is basically used in real life applications that involve large
amounts of data input and in such situations the console oriented I/O
operations pose two major problems:
• First, it becomes cumbersome and time consuming to handle huge
amount of data through terminals.
• Second, when doing I/O using terminal, the entire data is lost when
either the program is terminated or computer is turned off. Therefore,
it becomes necessary to store data on a permanent storage (the disks)
and read whenever necessary, without destroying the data
#include <stdio.h>
main()
{ Two kinds of files:
int i; – Textfile :: contains ASCII codes only EOF character can be
fprintf(stdout,"Give value of i \n"); checked
fscanf(stdin,"%d",&i); – Binaryfile :: can contain non-ASCII characters. Ex: Image,
fprintf(stdout,"Value of i=%d \n",i); audio, video, executable, etc.
fprintf(stderr,"No error: message.\n"); To check the end of file here, the file size value (also stored on
} disk) needs to be checked. feof
Function Description
fopen() opens new or existing file

fprintf() write data into the file


fscanf() reads data from the file

fputc() writes a character into the file

fgetc() reads a character from file

fgets() reads a string from file


fputs() writes a string to file
getw() Read integer from the file
putw() Write an integer into the file
fread() Reads data from the file

fwrite() Write data into the file

fseek() sets the file pointer to given position

ftell() returns current position

rewind() sets the file pointer to the beginning of


the file
fclose() closes the file
Steps in File handling
• Declare the File Pointer: FILE *fp=NULL;
Other file operations:
• Open the file with specified mode: fp=fopen(“filename.txt”, “mode”);
fseek( fp, Position, SEEK_SET );
• Process the file using following functions
ftell(fp)
• fscanf and fprintf
rewind(fp)
Syntax: fscanf(fp, “format specifiers”, &variables);
Example: fscanf(fp, “%s %d”,&name,&rollno);
#include<stdio.h>
Syntax: fprintf(fp, “format specifiers”, variables);
void main()
Example: fprintf(fp, “%s %d”,name,rollno);
{
• fgetc and fputc
FILE*fp=fopen("1.txt",“w");
Syntax: ch=fgetc(fp);
fseek(fp, 5,SEEK_SET);
Syntax:fputc(ch,fp);
fputs(“Soul”);
• fgets and fputs
printf(“Pos is %ld”,ftell(fp));
syntax: fgets(str,number of characters, fp);
rewind(fp);
syntax:fputs(str,fp);
printf(“Pos is %ld”,ftell(fp));
• fread and fwrite
fclose(fp);
Syntax: fread(void *ptr, size_t size, size_t n, FILE *fp);
}
Example:int a[5];
Input:1.txt
fread(a,sizeof(int),2,fp);
Good makes happy
Syntax: fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
Output:1.txt
Example:
Good soul makes happy
int a[]={10,20};
Pos is 9
fwrite(a,sizeof(int),2,fp);
Pos is 0
• Close the file: fclose(fp);
1 2 3
#include<stdio.h> #include<stdio.h> #include<stdio.h>
void main() void main() void main()
{ { {
FILE*fp1=fopen("1.txt","r"); FILE*fp1=fopen("1.txt","r"); FILE*fp1=fopen(“in.txt","r");
FILE*fp2=fopen("2.txt",“w"); FILE*fp2=fopen("2.txt","w"); FILE*fp2=fopen("res.txt","w");
while(1) char line[100]; int a,b;
{ while(fgets(line,80,fp1)!=NULL) fscanf(fp1,"%d %d",&a,&b);
char ch=fgetc(fp1); { fprintf(fp2,"Result is %d",a+b);
if(ch==EOF) fputs(line,fp2); fclose(fp1);
break; fclose(fp2);
printf("%c",ch); } }
fputc(ch,fp2); fclose(fp1); #include<stdio.h>
} fclose(fp2); 4
void main()
fclose(fp1); } {
fclose(fp2); FILE*fp1=fopen("src.txt","r");
} FILE*fp2=fopen("dst.txt","w");
1)Input: 2)input: 3) Input 4)input
char a[100];
1.txt 1.txt in.txt src.txt
fread(a,sizeof(char),3,fp1);
Welcome to KCET Welcome to KCET 10 20 God is great
fwrite(a,sizeof(char),3,fp2);
CSE CSE
fclose(fp1);
Output: output: 2.txt output: res.txt output: dst.txt
fclose(fp2);
Welcome to KCET Welcome to KCET Result is 30 God
}
CSE CSE
File copy Write and Read File contents

#include<stdio.h>
int main(){
#include <stdio.h> char ch;
void main () FILE *fp;
{ fp=fopen("std1.txt","w"); //opening file in write mode
FILE *fp = fopen("src.txt","r"); printf("enter the text.press cntrl Z:");
FILE *fp1 = fopen("dst.txt","w"); while((ch = getchar())!=EOF){
if (fp == NULL) putc(ch,fp); // writing each character into the file
do }
{ fclose(fp);
char c = fgetc(fp); fp=fopen("std1.txt","r");
if (feof(fp)) printf("text on the file: ");
break ; while ((ch=getc(fp))!=EOF){ // reading each character from file
putchar(ch); // displaying each character on to the screen
printf("%c", c); }
fputc(c,fp1); fclose(fp);
} while(1); return 0;
fclose(fp); }
fclose(fp1);
}
Read and Write a Integer values in file
#include<stdio.h>
int main( ){
FILE *fp;
int i;
fp = fopen ("num.txt", "w");
for (i =1; i<= 10; i++){
putw (i, fp);
}
fclose (fp);
fp =fopen ("num.txt", "r");
printf ("file content is");
for (i =1; i<= 10; i++){
i= getw(fp);
printf ("%d",i);
printf("");
}
fclose (fp);
return 0;
}
#include<stdio.h>
struct student{
int sno; fp = fopen ("student1.txt", "r");
char sname [30]; for (i=0; i<60; i++){
char gender; printf ("details of student %d are ", i+1);
float avg; fread (&s[i], sizeof (s[i]) ,1,fp);
}; printf("student number = %d ", s[i]. sno);
void main ( ){ printf("student name = %s ", s[i]. sname);
struct student s[60]; printf("student gender = %c ", s[i]. gender);
int i; printf("student avg = %f ", s[i]. avg);
FILE *fp; }
fp = fopen ("student1.txt", "w"); fclose(fp);
for (i=0; i<60; i++){
printf ("enter details of student %d", i+1); }
printf("student number:");
scanf("%d",&s[i].sno);
printf("student name:"); Write and Read of student record in file
gets(s[i].sname);
printf("student gender:");
scanf("%c",&s[i].gender);
printf("student avg:");
scanf("%f",&s[i].avg);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fclose (fp);
#include <stdio.h>
#include <stdlib.h>
int main()
{ File Merge
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged file1.txt and file2.txt into file3.txt");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
UNIT V- Advanced C Concepts
BIT-FIELD #include <stdio.h>
The idea of bit-field is to use memory
struct date
efficiently when we know that the value of a {
field or group of fields will never exceed a int d : 5; // d range is 0 - 31, so 5 bits are sufficient
limit or is within a small range. int m : 4; // m range is 0 - 15, so 4 bits are sufficient
Bit fields are used when the storage of our int y;
program is limited. };
int main()
Need of bit fields in C programming language: {
• Reduces memory consumption. printf("Size of date is %lu bytes\n", sizeof(struct date));
• To make our program more efficient and flexible. struct date dt = { 15, 07, 2023 };
• Easy to Implement printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
Syntax: }
struct tagname
{ Output:
type member: width_of_bit-field; Size of date is 8 bytes
Date is 15/07/2023
typedef
The typedef is a keyword
used in C programming to
provide some meaningful
names to the already existing
type/variable in the C
Program.

Syntax :
typedef <existing_name> <alias_name> ;
MACRO is defined with the pre-processor directive.
• Macros are pre-processed which means that all the macros would be
processed before your program compiles
Preprocessing
Occurs before a program is compiled
Inclusion of other files Types of Macro
Definition of symbolic constants and macros
Conditional compilation of program code
Conditional execution of preprocessor directives
Format of preprocessor directives
Lines begin with #
Only whitespace characters before directives on a line
Predefined Macros
Object Like Macro Function Like Macro

Syntax: #define Macrofunction(args) operations


Example: #define sum(a,b) a+b
Condition Like Macros Conditional compilation
Control preprocessor directives and compilation
#ifndef Macro Cast expressions, sizeof, enumeration
//conditional code constants cannot be evaluated
#endif
•The unconditional directives are:
• #include - Inserts a particular header from another file. Ex: #include “file1.h”
• #define - Defines a preprocessor macro. Ex: #define MSG "You wish!"
• #undef - Undefines a preprocessor macro. Ex: #undef MSG
•The conditional directives are:
• #ifdef - If this macro is defined // #ifdef short for #if defined(name)
• #ifndef - If this macro is not defined //#ifndef short for #if !defined(name)

#if !defined ( NULL ) #define DEBUG 1


#define NULL 0 #ifdef DEBUG
#endif printf (“ Variable x = %d \n”, x) ;
#endif

• #if - Test if a compile time condition is true


#if 0
code commented out
#endif
• #else - The alternative for #if
• #elif - #else an #if in one statement
• #endif - End preprocessor conditional
•Other directives include:
• # - Stringization, replaces a macro parameter with a string constant
• ## - Token merge, creates a single token from two adjacent ones
# Replacement text token converted to string with quotes
#define HELLO( x ) printf (“ Hello, “ #x “\
n”);
HELLO(John)
becomes
printf (“ Hello, “ “John” “\n”);
printf (“ Hello, John\n”);
## Concatenates two tokens
Strings separated by whitespace are concatenated
#define TOKENCONCAT( x, y ) x ## y
TOKENCONCAT( O, K )
becomes
OK

• assert macro
Header <assert.h>
Tests value of an expression
If 0 (false) prints error message and calls abort
assert( x <= 10 );
If NDEBUG defined...
All subsequent assert statements ignored
#define NDEBUG
Variable length Arguments #include <stdio.h>
#include <stdarg.h>
double average ( int num, ... )
• Creating a Variadic Function {
• Use standard header stdarg.h va_list ap;
• 4 macros (not prototypes) needed from this double sum = 0;
header file va_start ( ap, num ); //initializes, store all values
va_list int x;
va_start for ( x = 0; x < num; x++ )
va_arg sum += va_arg ( ap, double );
va_end va_end ( ap );
return sum/num;
}
int main()
{
printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ));
printf("%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ));
return 0;
}
Command Line Arguments are passed to the main() method.
In order to implement command line arguments, generally, two parameters
are passed into the main function:
Number of command line arguments (argc): It refers to “argument count”.
The list of command line arguments (argv): It refers to “argument vector”.
The basic syntax is: #include <stdio.h>
#include <conio.h>
int main( int argc, char *argv[] )
void main(int argc, char *argv[])
{ {
. printf(“No of cmd args are %d”,argc);
for(int i = 0; i < argc; i++)
.
printf("%s\t", argv[i]);
// BODY OF THE MAIN FUNCTION }
.
Input: ./a.out 2 ram raj
.
Output:
} No of cmd args are 4
./a.out 2 ram raj
Recursive Function:
A Function call itself again and again to solve the problem.
Base Case + Recursive Case = Recursive Function
Base Case: The condition that stops the recursion. It is simple, solvable case of the problem that does not require
further recursion
Recursive Case: The part of the recursion that breaks the problem down into smaller subproblems, leading closer
to the base case. It involves a function calling itself.
Finding Factorial a Number Using Recursion
Recursion Tree
#include <stdio.h>

int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

int main() {
int n;
printf("Enter the number of elements to be in the series : ");
scanf("%d", &n);
for (int i = 0; i < n; i++) { Input:
printf("%d, ", fibonacci(i)); 8
} Output:
return 0; 0, 1, 1, 2, 3, 5, 8, 13,
}
#include <stdio.h>
int sum(int n,int a[])
{
if ( n <0 )
return 0;
else
return a[n]+sum(n-1,a);

}
int main() {
int a[100],N;
printf("Enter size of the array: ");
scanf("%d", &N);
printf("Enter elements in the array: ");
for(int i=0; i<N; i++)
{
scanf("%d", &a[i]);
}
int result=sum(N,a);
printf("%d",result);

return 0;
}
Modular programming is a software design technique that
How do you solve a big/complex?
emphasizes separating the technique that emphasizes
Divide it into small tasks and solve each task.
separating the functionality of a functionality of a program into Then combine these solutions.
Modules can be written and tested separately
independent, interchangeable modules, such that each
Modules can be reused
contains everything necessary to execute only one aspect of Large projects can be developed in parallel
Reduces length of program, making it more
the desired functionality.
readable
Promotes the concept of abstraction
Features of Modular Programming  A module hides details of a task
Helps manage complexity  We just need to know what this module
 Smaller blocks of code does
 Easier to read  We don’t need to know how it does it
Encourages re-use of code
 Within a particular program or across different programs
Allows independent development of code
User-defined libraries
User defined libraries are created and maintained by programmers.
They can contain user defined functions to perform specific tasks

To add a user-defined library to your program, you need to perform the following steps:
1. Write the code for the library: This involves writing the functions that will be included
in the library.
2. Compile the code: Compile the code for the library into an object file (usually with
filename.o or .obj extension) using the appropriate compiler.
3. Create the library: create a library file (usually with filename. a extension ) from the
object file. The library file contains the compiled code for the functions in the library.
4. Link the library to your program: To use the library in your program, you need to link
the library file to the program at compile time. This can be done using linker scripts.
5. Include the header file: In order to call the functions in the library, you need to
include the header file for the library in your program
Example of how to add a user-defined library in C: (Using Command Prompt in Windows or linux)
ar stands for "archiver", which is a tool used to manage libraries in C
•r: replace existing files in the library
•c: create the library if it does not exist
•s: write an index to the archive, allowing faster access to its contents
•libmylib.a is the name of the library file that will be created,
•mylib.o is the name of the object file that will be included in the library.

•gcc is the Gnu Compiler Collection, which includes a C compiler


•-L. specifies the directory where the library file is located. The . means the current
directory.
•-lmylib specifies the library to be linked with the program.
•-o main specifies the name of the output file
5. Include mylib.c in the header file
// main.c
#include <stdio.h>
#include "mylib.c"
int main(){ 6. Run the main.c
print_hello(); C:\> ./main
return 0; Output:
} Hello, World!

You might also like