0% found this document useful (0 votes)
15 views

File Handling

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)
15 views

File Handling

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/ 31

1

FILE HANDLING IN ‘C’

➢ A file represents a sequence of bytes on the disk where a group of related data is stored.
➢ File is created for permanent storage of data. It is a readymade structure.
➢ In C language, we use a structure pointer of file type to declare a file.
➢ C provides a number of functions that helps to perform basic file operations. Following
are the functions:

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the beginning point


2

Types of Files :
When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files

1. Text files

➢ Text files are the normal .txt files.


➢ You can easily create text files using any simple text editors such as Notepad.
➢ When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents.

➢ They take minimum effort to maintain, are easily readable, and provide the least security
and takes bigger storage space.

2. Binary files

➢ Binary files are mostly the .bin files in your computer.


➢ Instead of storing data in plain text, they store it in the binary form (0's and 1's).

➢ They can hold a higher amount of data, are not readable easily, and provides better
security than text files

Difference between Text File and Binary File:

Text File Binary File

Bits represent character. Bits represent a custom data.

Less prone to get corrupt as changes reflect as


soon as the file is opened and can easily be Can easily get corrupted, even a single bit
undone. change may corrupt the file.

Can store different types of data (image,


Can store only plain text in a file. audio, text) in a single file.

Widely used file format and can be opened Developed especially for an application and
using any simple text editor. may not be understood by other applications.

Mostly .txt and .rtf are used as extensions to


text files. Can have any application defined extension.
3

Operations in FILE :

➢ A File can be used to store a large volume of persistent data. Following are some
operations which can be performed in a file.

1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

❖ Creating and Opening a File

➢ Whenever you want to work with a file, the first step is to create a file. A file is nothing
but space in a memory where data is stored.

➢ To create a file in a 'C' program following syntax is used,

FILE *fp;
fp = fopen ("file_name", "mode");

fp is a file pointer which points to the type file.

In the above syntax, the file is a data structure which is defined in the standard library.

Example 1:

#include <stdio.h>
void main()
{
FILE *fp;
fp =fopen ("data.txt", "w");
}

Output:

File is created in the same folder where you have saved your code.

Example 2:

You can specify the path where you want to create your file

#include <stdio.h>

int main() {
FILE *fp;
fp =fopen ("D://data.txt", "w");
}
➢ The fopen() function is used to create a new file or to open an existing file.
➢ If the file is not present on the system, then it is created and then opened.
4

➢ If a file is already present on the system, then it is directly opened using this function.

Mode in File

➢ Whenever you open or create a file, you have to specify what you are going to do with the
file. A file in 'C' programming can be created or opened for reading/writing purposes. A
mode is used to specify whether you want to open a file for any of the below-given
purposes.

Following are the different types of modes in 'C' programming which can be used while
working with a file.

Mode Description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode


5

What if the file already exists?


If a file with the same name already exists, its contents are discarded and the file is treated as
a new empty file.

For example, in the following program, if “test.txt” already exists, its contents are removed
and “VSSUT” is written to it.

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE*fp = fopen("test.txt", "w");
if(fp == NULL)
{
puts("Couldn't open file");
exit(0);
}
else
{
fputs("VSSUT", fp);
puts("Done");
fclose(fp);
}
return 0;
}
The above behaviour may lead to unexpected results. If programmer’s intention was to create
a new file and a file with same name already exists, the existing file’s contents are
overwritten.
The latest C standard C11 provides a new mode “x” which is exclusive create-and-open
mode. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”. When x is used with
w, fopen() returns NULL if file already exists or could not open.

Following is the modified program that doesn’t overwrite an existing file.


#include <stdio.h>
6

#include <stdlib.h>

int main()
{
FILE*fp = fopen("test.txt", "wx");
if(fp == NULL)
{
puts("Couldn't open file or file already exists");
exit(0);
}
else
{
fputs("VSSUT", fp);
puts("Done");
fclose(fp);
}
return 0;
}

❖ Closing a File :
➢ The fclose() function is used to close an already opened file.
General Syntax :
fclose( file_ptr);.

Example:

FILE *fp;
fp =fopen ("data.txt", "r");
fclose (fp);

➢ In 'C' programming, files are automatically close when the program is terminated.
7

• Writing to a File:

• fputc()
-The is used to writing a character to a file
Syntax:
fputc(character,file_pointer);

EXAMPLE :
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory
and writes two lines using two different functions. In C, when you write to a file, newline
characters '\n' must be explicitly added.

The program below shows how to perform writing to a file:

EXAMPLE1:

#include <stdio.h>
int main()
{
inti;
FILE * fptr;
char fn[50];
char str[] = "HELLO VSSUT\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++)
{
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr);
return 0;
}

Output: HELLO VSSUT


8

The above program writes a single character into the fputc_test.txt file until it reaches the
next line symbol "\n" which indicates that the sentence was successfully written. The process
is to take each character of the array and write it into the file.

1. In the above program, we have created and opened a file called fputc_test.txt in a
write mode and declare our string which will be written into the file.
2. We do a character by character write operation using for loop and put each character
in our file until the "\n" character is encountered then the file is closed using the
fclose() function.

• fputs () Function:

-fputs () function writes string to a file.


Syntax:
fputs(string,file_pointer);

Example:

#include <stdio.h>
intmain() {
FILE * fp;
fp = fopen("fputs_test.txt", "w+");
fputs("This is demo of fputs,", fp);
fputs("We don't need to use for loop\n", fp);
fputs("Easier than fputc function\n", fp);
fclose(fp);
return (0);
}

OUTPUT:

This is demo of fputs, We don't need to use for loop

Easier than fputc function

1. In the above program, we have created and opened a file called fputs_test.txt in a
write mode.
2. After we do a write operation using fputs() function by writing three different strings

3.Then the file is closed using the fclose() function.

• fprintf()Function:

-works just like printf() except that its first argument is a file pointer.
Syntax:
fprintf(file_pointer, “control string”, list);
9

Example:

#include <stdio.h>
intmain() {
FILE *fptr;
fptr = fopen("fprintf_test.txt", "w"); // "w" defines "writing mode"
/* write to file */
fprintf(fptr, "Hello VSSUT\n");
fclose(fptr);
return 0;
}

OUTPUT:

Hello VSSUT

1. In the above program we have created and opened a file called fprintf_test.txt in a
write mode.
2. After a write operation is performed using fprintf() function by writing a string, then
the file is closed using the fclose() function.

Example 1: Write to a text file

#include<stdio.h>
#include<stdlib.h>

int main()
{
int num;
FILE *fptr;

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

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return0;
}

This program takes a number from the user and stores in the file program.txt.
10

After you compile and run this program, you can see a text file program.txt created in C drive
of your computer. When you open the file, you can see the integer you entered.

Reading from a File:


Given below is the simplest function to read a single character from a file −
• fgetc()
- fgetc functions is used to read a character from a file. It reads single character at a time.
Syntax

fgetc( FILE * fp );

• fgets()
-fgets function is used to read a file line by line
Syntax
fgets (buffer, size, fp);

where
buffer – buffer to put the data in.

size – size of the buffer

fp – file pointer

fscanf()
fscanf(FILE *fp, const char *format, ...)
This function is used to read strings from a file, but it stops reading after encountering the
first space character or newline.
#include <stdio.h>
main() {

FILE *fp;
char buff[255];

fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );
fclose(fp);
11

}
When the above code is compiled and executed, it reads the file created in the previous
section and produces the following result −
1 : This
2: is testing for fprintf...

3: This is testing for fputs...


Here first, fscanf() read just This because after that, it encountered a space, second call is
for fgets() which reads the remaining line till it encountered end of line. Finally, the last
call fgets() reads the second line completely.
Example:

The following program demonstrates reading from fputs_test.txt file using


fgets(),fscanf() and fgetc () functions respectively :

#include <stdio.h>
intmain() {
FILE * file_pointer;
char buffer[30], c;

file_pointer = fopen("fprintf_test.txt", "r");


printf("----read a line----\n");
fgets(buffer, 50, file_pointer);
printf("%s\n", buffer);

printf("----read and parse data----\n");


file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
char str1[10], str2[2], str3[20], str4[2];
fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
printf("Read String1 |%s|\n", str1);
printf("Read String2 |%s|\n", str2);
printf("Read String3 |%s|\n", str3);
printf("Read String4 |%s|\n", str4);

printf("----read the entire file----\n");

file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer


while ((c = getc(file_pointer)) != EOF) printf("%c", c);
fclose(file_pointer);
return 0;
}

Result:

----read a line----
Learning FILEin C
12

----read and parse data----


Read String1 |Learning|
Read String2 |FILE|
Read String3 |in|
Read String4 |C|
----read the entire file----
Learning FILE in C

1. In the above program, we have opened the file called "fprintf_test.txt" which was
previously written using fprintf() function, and it contains "Learning FILE in C"
string. We read it using the fgets() function which reads line by line where the buffer
size must be enough to handle the entire line.
2. We reopen the file to reset the pointer file to point at the beginning of the file. Create
various strings variables to handle each word separately. Print the variables to see
their contents. The fscanf() is mainly used to extract and parse data from a file.
3. Reopen the file to reset the pointer file to point at the beginning of the file. Read data
and print it from the file character by character using getc() function until the EOF
statement is encountered
4. After performing a reading operation file using different variants, we again closed the
file using the fclose function.

Example 2: Read from a text file

#include<stdio.h>
#include<stdlib.h>

intmain()
{
intnum;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return0;
This program reads the integer present in the program.txt file and prints it onto the screen. If
you successfully created the file from above example , running this program will get you the
integer you entered.
13

Difference between getc(), getchar(), getch() and getche():

All of these functions read a character from input and return an integer value. The integer is
returned to accommodate a special value used to indicate failure. The value EOF is generally
used for this purpose.
1) getc():
It reads a single character from a given input stream and returns the corresponding
integer value (typically ASCII value of read character) on success. It returns EOF on
failure.
Syntax:
getc(FILE *stream);
Example for getc()
#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return(0);
}
Input: g (press enter key)
Output: g
An Example Application : C program to compare two files and report mismatches.
2) getchar():
The difference between getc() and getchar() is getc() can read from any input stream,
but getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);
Example:
// Example for getchar() in C
#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
Input: g(press enter key)
Output: g
3) getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly
used by MS-DOS compilers like Turbo C.
-Like above functions, it reads also a single character from keyboard. But it does not
use any buffer, so the entered character is immediately returned without waiting for
the enter key.
14

Syntax:

getch();
Example:
// Example for getch() in C
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
return 0;
}
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
4) getche()
-Like getch(), this is also a non-standard function present in conio.h. It reads a single
character from the keyboard and displays immediately on output screen without waiting for
enter key.
Syntax:
getche(void);
Example:

#include <stdio.h>
#include <conio.h>
// Example for getche() in C
intmain()
{
printf("%c", getche());
return 0;
}
Input: g(without enter key as it is not buffered)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
double g, i.e., 'gg'

Some More Examples:

Input/output operation on File


file I/O functions to perform reading and writing on file. getc() and putc() are the simplest
functions which can be used to read and write individual characters to a file.
15

#include<stdio.h>

intmain()

FILE *fp;

char ch;

fp=fopen("one.txt","w");

printf("Enter data...");

while((ch=getchar())!= EOF){

putc(ch,fp);

fclose(fp);

fp=fopen("one.txt","r");

while((ch=getc(fp)!= EOF)

printf("%c",ch);

// closing the file pointer

fclose(fp);

return0;

Interactive File Read and Write with getc() and putc()

These are the simplest file operations. Getc() stands for get character, and putc() stands for
put character. These two functions are used to handle only a single character at a time.

Following program demonstrates the file handling functions in 'C' programming:

#include <stdio.h>
int main() {
FILE * fp;
char c;
printf("File Handling\n");
//open a file
fp = fopen("demo.txt", "w");
//writing operation
while ((c = getchar()) != EOF) {
putc(c, fp);
16

}
//close file
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);
return 0;
}

Output:

File Handling

Hello VSSUT

Data Entered:

Hello VSSUT

1. In the above program we have created and opened a file called demo in a write mode.
2. After a write operation is performed, then the file is closed using the fclose function.
3. We have again opened a file which now contains data in a reading mode. A while
loop will execute until the eof is found. Once the end of file is found the operation
will be terminated and data will be displayed using printf function.
4. After performing a reading operation file is again closed using the fclose function.

Reading and Writing to File using fprintf() and fscanf()

#include<stdio.h>

struct emp

char name[10];

int age;

};

void main()

struct emp e;
17

FILE *p,*q;

p =fopen("one.txt","a");

q =fopen("one.txt","r");

printf("Enter Name and Age:");

scanf("%s %d", e.name,&e.age);

fprintf(p,"%s %d", e.name,e.age);

fclose(p);

do

fscanf(q,"%s %d", e.name,e.age);

printf("%s %d", e.name,e.age);

while(!feof(q));

In this program, we have created two FILE pointers and both are refering to the same file but
in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can
then be printed on the console using standard printf() function.

Difference between Append and Write Mode:


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exist already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will
not happen. Append mode is used to append or add data to the existing data of file (if any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the
present data in the file.

Reading and writing to a binary file:


Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
18

Writing to a binary file:

To write into a binary file, you need to use the fwrite() function. The functions take four
arguments:
address of data to be written in the disk
size of data to be written in the disk
number of such type of data
pointer to the file where you want to write.
fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 1: Write to a binary file using fwrite()

#include<stdio.h>

#include<stdlib.h>

Struct threeNum

int n1, n2, n3;

};

int main()

int n;

struct threeNum num;

FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.


19

exit(1);

for(n = 1; n <5; ++n)

num.n1 = n;

num.n2 = 5*n;

num.n3 = 5*n + 1;

fwrite(&num, sizeof(struct threeNum), 1, fptr);

fclose(fptr);

return0;

In this program, we create a new file program.bin in the C drive.


We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the
main function as num.
Now, inside the for loop, we store the value into the file using fwrite().
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since we're only inserting one instance of num, the third parameter is 1. And, the last
parameter *fptr points to the file we're storing the data.
Finally, we close the file.
Reading from a binary file:
Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);

Example 2: Read from a binary file using fread()

#include<stdio.h>
20

#include<stdlib.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n <5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return0;
}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed
by *fptr into the structure num.
You'll get the same records you inserted in Example 2.

Getting data using fseek():


If you have many records inside a file and need to access a record at a specific position, you
need to loop through all the records before it to get the record. This will waste a lot of
memory and operation time. An easier way to get to the required data can be achieved
using fseek().As the name suggests, fseek() seeks the cursor to the given record in the file.

Sntax of fseek()

fseek(FILE * stream, longint offset, int whence);

The first parameter stream is the pointer to the file. The second parameter is the position of
the record to be found, and the third parameter specifies the location where the offset starts.

Different whence in fseek()


Whence Meaning
21

SEEK_SET Starts the offset from the beginning of the file.


SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location of the cursor in the file.

Example :fseek()

#include <stdio.h>

int main()
{
FILE *fp;
fp = fopen("test.txt", "r");

// Moving pointer to end


fseek(fp, 0, SEEK_END);

// Printing position of pointer


printf("%ld", ftell(fp));

return 0;
}
Output:
81

FEW MORE FILE PROGRAM EXAMPLES :

1. C program to read name and marks of n number of students and store them in a file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i<num; ++i)


{
printf("For student%d\nEnter name: ", i+1);
22

scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}
2. C program to read name and marks of n number of students from and store them in
a file. If the file previously exits, add the information to the file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i<num; ++i)


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}
23

3. C Program to Print names of all Files present in a Directory

#include<stdio.h>

#include<dirent.h>

int main(void)

DIR *d;

structdirent *dir;

d = opendir(".");

if (d)

while ((dir = readdir(d)) != NULL)

printf("%s\n", dir->d_name);

closedir(d);

return(0);

File1.txt

File2.txt

File3.txt

File4.txt

File5.txt

File6.txt

File7.txt

dirent.h header file contains variables and functions related to directory streams.
24

We can also take the directory name as input from the user, and can also create a simple C
program to search for a particular file in a directory.

4) C Program to Read content of a File and Display it

#include<stdio.h>

#include <stdlib.h> // for exit() function

intmain()

char c[1000];

FILE *fptr;

if ((fptr = fopen("studytonight.txt", "r")) == NULL)

printf("Error! opening file");

// exit from program if file pointer returns NULL.

exit(1);

// read the text until newline

fscanf(fptr,"%[^\n]", c);

printf("Data from the file:\n%s", c);

fclose(fptr);

return 0;

Data from the file:


25

/* Data in the file will get printed. */

5)C Program to find the Size of any File


We will be using fseek() and ftell() functions to find the size of the file. There are others
ways to find the file size as well, like looping on the whole content of file and finding out the
size, but the File Handling functions makes it a lot easier.
Below is a program to find size of file.

#include<stdio.h>

#include<conio.h>

void main()

{ FILE *fp;

char ch;

int size = 0;

fp = fopen("MyFile.txt", "r");

if (fp == NULL)

printf("\nFile unable to open...");

else

printf("\nFile opened...");

fseek(fp, 0, 2); /* File pointer at the end of file */

size = ftell(fp); /* Take a position of file pointer in size variable */

printf("The size of given file is: %d\n", size);

fclose(fp);

6) C Program to create a File & write Data in it

#include<stdio.h>
26

#include<conio.h>

void main()

FILE *fptr;

char name[20];

int age;

float salary;

/* open for writing */

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

if (fptr == NULL)

printf("File does not exist.\n");

return;

printf("Enter the name:\n");

scanf("%s", name);

fprintf(fptr, "Name = %s\n", name);

printf("Enter the age:\n");

scanf("%d", &age);

fprintf(fptr, "Age = %d\n", age);

printf("Enter the salary:\n");

scanf("%f", &salary);

fprintf(fptr, "Salary = %.2f\n", salary);

fclose(fptr);
27

You can add any information in the file, like we have added Name, Age and Salary for some
employees, you can change the program as per your requirements.
You can even initialise a for loop, to add details of multiple employees to the file. All you
have to do is, ask user for number of employees for which data has to be stored, run
the for loop that many times and keep on adding the data to the file.

7) C Program to reverse the content of a File

#include<stdio.h>

#include<errno.h>

/* to count the total number of characters inside the source file*/

long count_characters(FILE *);

void main()

int i;

long cnt;

char ch, ch1;

FILE *fp1, *fp2;

if (fp1 = fopen("File_1.txt", "r"))

printf("The FILE has been opened...\n");

fp2 = fopen("File_2.txt", "w");

cnt = count_characters(fp1);/* Make the pointer fp1 to point at the last character of the file
*/

fseek(fp1, -1L, 2);

printf("Number of characters to be copied %d\n", ftell(fp1));

while (cnt)

ch = fgetc(fp1);
28

fputc(ch, fp2);

fseek(fp1, -2L, 1); // shifts the pointer to the previous character

cnt--;

printf("\n**File copied successfully in reverse order**\n");

else

perror("Error occured\n");

fclose(fp1);

fclose(fp2);

/* Count the total number of characters in the file that *f points to */

long count_characters(FILE *f)

fseek(f, -1L, 2);

/* returns the position of the last element of the file */

long last_pos = ftell(f);

last_pos++;

return last_pos;

8) C Program to copy content of one File into another File

#include<stdio.h>

#include<stdio.h>

void main()

{
29

/* File_1.txt is the file with content and, File_2.txt is the file in which content of File_1 will
be copied */

FILE *fp1, *fp2;

char ch;

intpos;

if ((fp1 = fopen("File_1.txt", "r")) == NULL)

printf("\nFile cannot be opened.");

return;

else

printf("\nFile opened for copy...\n ");

fp2 = fopen("File_2.txt", "w");

fseek(fp1, 0L, SEEK_END); // File pointer at end of file

pos = ftell(fp1);

fseek(fp1, 0L, SEEK_SET); // File pointer set at start

while (pos--)

ch = fgetc(fp1); // Copying file character by character

fputc(ch, fp2);

fcloseall();

Command Line Arguments


30

-Command line argument is a parameter supplied to the program when it is invoked.


-It is mostly used when you need to control your program from outside. Command line
arguments are passed to the main() method.
Syntax:
int main(int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ] is a pointer array
which holds pointers of type char which points to the arguments passed to the program.
Example:
#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])


{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
31

- argv[0] holds the name of the program and argv[1] points to the first command line
argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.

QUESTIONS:

1. Write a program in C to create and store information in a text file.


2. Write a program in C to read the file and store the lines into an array.
3. Write a program in C to count a number of words and characters in a file.
4. Write a program in C to merge two files and write it in a new file.
5. C program to find the sum of N integer numbers using command line arguments.

You might also like