0% found this document useful (0 votes)
49 views49 pages

M5 C Notes

1) Files allow applications to permanently store and access information as needed. C provides functions to create, open, read, and write to both text-based stream files and binary unformatted files. 2) To work with a file, it must first be opened using fopen() which associates a file name with a buffer. Files can then be read from or written to using functions like fread(), fwrite(), fgetc(), fputc() until the file is closed with fclose(). 3) Unformatted files use fread() and fwrite() to randomly access complex data structures like arrays from files, while text files contain sequential characters accessed with scanf() and printf(). Opening files with

Uploaded by

Aa Aa
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)
49 views49 pages

M5 C Notes

1) Files allow applications to permanently store and access information as needed. C provides functions to create, open, read, and write to both text-based stream files and binary unformatted files. 2) To work with a file, it must first be opened using fopen() which associates a file name with a buffer. Files can then be read from or written to using functions like fread(), fwrite(), fgetc(), fputc() until the file is closed with fclose(). 3) Unformatted files use fread() and fwrite() to randomly access complex data structures like arrays from files, while text files contain sequential characters accessed with scanf() and printf(). Opening files with

Uploaded by

Aa Aa
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/ 49

File manipulation

FILES
Many applications require information be to be read from or written to an auxiliary memory device. Such
information is stored on the memory device in the form of a data file. Thus, data files allow us to store the
information permanently, and to access and alter that information whenever necessary.
In C, an extensive set of library functions is available for creating and processing data files. Unlike other
Programming languages, C does not distinguish between sequential and direct access (random access)
data Files. However, there are two different types of data files, called stream-oriented or standard data
files, and system-oriented or low-level data files. Stream-oriented data files are easier to work with and are
more commonly used. Stream-oriented data files are subdivided into text files and unformatted data files.
Text files that are Sequential files consist of consecutive characters that are interpreted as individual data
items using scanf and printf functions where as unformatted data files, organizes data into blocks which
contains contiguous bytes of information involving complex data structures, like arrays and structures.

OPENING AND CLOSING A DATA FILE


When working with a stream-oriented data file, data is read and modified sequentially. The first step is to
establish a buffer area, where information has to be temporarily stored while being transferred between
the computer‟s memory and the data file. This buffer area allows information to be read from or written to
the data file.
The buffer area is established by writing
FILE *ptvar;
where FILE (uppercase letters required) is a special structure type that establishes the buffer area, and
ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type FILE is
defined within the system include file, stdio.h. The pointer ptvar is often referred to as a stream pointer.
A data file must be opened before it can be created or processed. This associates the file name with the
buffer area (i.e., stream). It also specifies how the data file should be utilized, whether as a read-only file,
a write-only file, or as a read-write file.

The library function fopen is used to open a file which is written as,
ptvar = fopen(file-name, file-type);
where file-name and file- type are strings that represent the name of the data file and file-type denotes the
manner in which the data file will be utilized.
e.g fp=fopen(“data.txt”,”r”); // open the file data.txt in read mode
The fopen function returns a pointer to the beginning of the buffer area associated with the file.
A NULL value is returned if the file cannot be opened as, for example, when an existing data file cannot
be found.
Finally, a data file must be closed at the end of the program. This can be accomplished with the library
function fclose. The syntax is:
fclose (ptvar);
Table 12-1 File-Type Specifications
File-Type Meaning
“r” Open an existing file for reading only.
“w” Open a new file for writing only. If a file with the specified file-name currently exists, it
will be destroyed and a new file created in its place.
“a” Open an existing file for appending (i.e., for adding new information at the end of the file).
A new file will be created if the file with the specified file-name does not exist.
“r+” Open an existing file for both reading and writing.
“w+” Open a new file for both reading and writing. If a file with the specified file-name currently
exists, it will be destroyed and a new file created in its place.
“a+” Open an existing file for both reading and appending. A new file will be created if the file
with the specified file-name does not exist.

1
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

/* read a line of lowercase text and store in uppercase within a data file */
#include <stdio.h>
#include <ctype.h>
int main( )
{
FILE * fpt ; / * define a pointer to predefined structure type FILE */
char c;
/* open a new data file for writing only*/
fpt = fopen("sample.dat", "w");

/* read each character and write its uppercase equivalent to the data file */
do
{
putc(toupper(c = getchar()), fpt ) ;
while (c != „\n‟) ;
/ * close the data file */
fclose (fpt) ;
}
After the program has been executed, the data file sample. dat will contain an uppercase equivalent of the
line of text entered into the computer from the keyboard.

For example, if the original line of text had been


We, the people of our country India

After processing, the data file would contain the text


WE, THE PEOPLE OF OUR COUNTRY INDIA

UNFORMATTED DATA FILES (Random access Files)


In Random access files, data is read and modified randomly To read and write blocks of contiguous data
representing a structure or an array, we use the library functions fread() and fwrite().These functions are
often referred to as unformatted read and write functions. Similarly, data files of this type are often
referred to as unformatted data files.

Each of these functions requires four arguments: a pointer to the data block, the size of the data block, the
number of data blocks being transferred, and the stream pointer.

Thus, a typical fwrite function is written as


fwrite(&customer, sizeof(record), 1, fpt) ;
where customer is a structure variable of type record, and fpt is the stream pointer associated with a data
file that has been opened for output.

Stream means reading and writing of data. Streams allow users to access files efficiently. A stream is a
file or physical device like keyboard, printer and monitor.
Figure below shows the input and output streams. The input stream brings data to the program and output
stream collects data from the program. In this way, Input stream extracts data from the file and transfers it
to the program while the output stream stores the data into the file provided by the program.

2
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

The FILE object uses all these devices. The FILE object contains all the information about stream like
current position, pointer to any buffer, EOF (end of file).
Other file functions are listed below:
Function Operation
fgetc() or getc() Reads a character from current pointer position and advances the pointer to next
character
fprintf() Writes all types of data values to the file
fscanf() Reads all types of data values from the file
fputc() or putc() Writes character one by one to file
gets() Reads string from file
puts() Writes string to file
putw() Writes an integer to the file
getw() Reads an integer from the file
fread() Reads structured data written by fwrite() function
fwrite() Writes block of structured data to the file
fseek() Sets the pointer position anywhere in the file
feof() Detects the End of File
ftell() Returns the current pointer position
rewind() Sets the record pointer at the beginning of the file
Opening File in Append mode E.g.
#include<stdio.h>
#include<process.h>
{ FILE *fp;
char c;
printf(“Contents of file before appending \n”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
{
c=fgetc(fp);
printf(“%c”,c);
}
fp=fopen(“data.txt”,”a”);
if(fp==NULL)
{
printf(“File cannot be appended”);

3
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

exit(1);
}
printf(“Enter string to append”);
while(c!=‟.‟)
{
c=getche();
fputc(c,fp);
}
fclose(fp);
printf(“\n Contents of File after appending”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
{
c=fgetc(fp);
printf(“%c”,c);
}
}
Contents of file before appending LMCST.
Enter string to append LOURDES MATHA COLLEGE OF SCIENCE AND TECHNOLOGY
Contents of File after appending LMCST. LOURDES MATHA COLLEGE OF SCIENCE AND
TECHNOLOGY

Create a text file and perform the following: a) write data to the file b) read the data in a given
file and display the file contents on console c) append new data and display on console.
Qn.) Write a C program to enter name and age to text file, use w+ file mode.
#include<stdio.h>
int main() {
FILE *fp;
char text[15];
int age,rollno;
float cgpa;
fp=fopen("Text.txt","w+");
printf("Enter Name and \t Age \n");
scanf("%s %d", text, &age);
fprintf(fp, "%s %d", text, age);
printf("Name \t Age \n");
fscanf(fp, "%s %d", text, &age);
printf("%s\t %d\n", text, age);
fp=fopen("Text.txt","a");
printf("Enter Roll no and CGPA \n");
scanf("%d %f", &rollno, &cgpa);
fprintf(fp, "%d %f", rollno, cgpa);
printf("Name \t Age \t Rollno \t CGPA\t\n ");
fscanf(fp, "%s %d %d %f", text, &age, &rollno , &cgpa);
printf("%s\t %d\t %d \t %f \n", text, age, rollno, cgpa);
fclose(fp);
}
Output
Enter Name and Age
Rini 18

4
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

Name Age
Rini 18

Enter Roll no and CGPA


33 85

Name Age Rollno CGPA


Rini 18 33 85

READ A LINE OF TEXT FROM A FILE

#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}

// reads text until newline is encountered


fscanf(fptr, "%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);

return 0;
}

Data from the file:


LOURDES MATHA COLLEGE OF SCIENCE AND TECHNOLOGY

Write a C program to count the no of lines, words, characters, spaces in a text file?
#include <stdio.h>
void main()
{
int line_cnt = 0, sp_cnt=0,ch_cnt=0,wrd_cnt=1;
FILE *fp;
char ch;
fp = fopen("txt1.txt", "r");
if(fp==NULL)
printf("\nError: file not found");
printf("\nFile Contents are:");
printf("\n-------------------\n");
ch = fgetc(fp);
while (ch != EOF)
{
printf("%c",ch);

5
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

/* read a line of lowercase text and store in uppercase within a data file */
#include <stdio.h>
#include <ctype.h>
int main( )
{
FILE * fpt ; / * define a pointer to predefined structure type FILE */
char c;
/* open a new data file for writing only*/
fpt = fopen("sample.dat", "w");

/* read each character and write its uppercase equivalent to the data file */
do
{
putc(toupper(c = getchar()), fpt ) ;
while (c != „\n‟) ;
/ * close the data file */
fclose (fpt) ;
}
After the program has been executed, the data file sample. dat will contain an uppercase equivalent of the
line of text entered into the computer from the keyboard.

For example, if the original line of text had been


We, the people of our country India

After processing, the data file would contain the text


WE, THE PEOPLE OF OUR COUNTRY INDIA

UNFORMATTED DATA FILES (Random access Files)


In Random access files, data is read and modified randomly To read and write blocks of contiguous data
representing a structure or an array, we use the library functions fread() and fwrite().These functions are
often referred to as unformatted read and write functions. Similarly, data files of this type are often
referred to as unformatted data files.

Each of these functions requires four arguments: a pointer to the data block, the size of the data block, the
number of data blocks being transferred, and the stream pointer.

Thus, a typical fwrite function is written as


fwrite(&customer, sizeof(record), 1, fpt) ;
where customer is a structure variable of type record, and fpt is the stream pointer associated with a data
file that has been opened for output.

Stream means reading and writing of data. Streams allow users to access files efficiently. A stream is a
file or physical device like keyboard, printer and monitor.
Figure below shows the input and output streams. The input stream brings data to the program and output
stream collects data from the program. In this way, Input stream extracts data from the file and transfers it
to the program while the output stream stores the data into the file provided by the program.

2
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

The FILE object uses all these devices. The FILE object contains all the information about stream like
current position, pointer to any buffer, EOF (end of file).
Other file functions are listed below:
Function Operation
fgetc() or getc() Reads a character from current pointer position and advances the pointer to next
character
fprintf() Writes all types of data values to the file
fscanf() Reads all types of data values from the file
fputc() or putc() Writes character one by one to file
gets() Reads string from file
puts() Writes string to file
putw() Writes an integer to the file
getw() Reads an integer from the file
fread() Reads structured data written by fwrite() function
fwrite() Writes block of structured data to the file
fseek() Sets the pointer position anywhere in the file
feof() Detects the End of File
ftell() Returns the current pointer position
rewind() Sets the record pointer at the beginning of the file
Opening File in Append mode E.g.
#include<stdio.h>
#include<process.h>
{ FILE *fp;
char c;
printf(“Contents of file before appending \n”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
{
c=fgetc(fp);
printf(“%c”,c);
}
fp=fopen(“data.txt”,”a”);
if(fp==NULL)
{
printf(“File cannot be appended”);

3
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

exit(1);
}

struct person input1 = {1, "royce", "anto"};


struct person input2 = {2, "rinil", "jose"};
//input1 and inut2 are structure variables
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);

if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");

// close file
fclose (outfile);
}
// C program for reading a block of data involving structure from a file
#include <stdio.h>
#include <stdlib.h>

// struct person with 3 fields


struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *infile;
struct person input;
// Open person.dat for reading
infile = fopen ("person.dat", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
// read file contents till end of file
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %s\n", input.id, input.fname, input.lname);

// close file
fclose (infile);
}
gcc demoread.c
./a.out
id = 1 name = royce anto
id = 2 name = rinil jose

8
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

Write a program to write and read the information about player containing players name, age and runs.
Use fread( ) and fwrite( ) functions?

#include<stdio.h>
#include<process.h>
struct record
{
int age;
int runs;
};
void main()
{
FILE *fp;
struct record emp;
fp=fopen(“record.dat”,”w”);
if(fp==NULL)
{
printf(“Cannot open file”);
exit(1);
}
printf(“Enter player name, age and runs scored”);
printf(“==============================”);
scanf(“%s %d %d”,emp.player, &emp.age,&emp.runs);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
if(fp=fopen(“record.dat”,”r”))==NULL)
{
printf(“error in opening file”);
exit(1);
}
printf(\n Record entered is\n”);
fread(&emp,sizeof(emp),1,fp);
printf(“%s %d %d”,emp.player, emp.age, emp.runs);
fclose(fp);
}

OUTPUT
Enter player name, age and runs scored
=============================
Arun 25 10000

Record entered is
Arun 25 10000

fseek() function
It is a file function used to position file pointer on the stream. Three arguments are passed through this
function:
 File pointer
 Negative or Positive number used to re-position file pointer towards backward or forward
direction.
 The current position of the file pointer

9
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

}
Output
gcc pgm.c
$ ./a.out
Enter name of first file a.txt
Enter name of second file b.txt
Enter name to store merged file merge.txt
Two files merged merge.txt successfully.

fwrite() function
The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a
structure. The Syntax of fwrite() function is as shown below:
fwrite( ptr, int size, int n, FILE *fp );
The fwrite() function takes four arguments.
ptr : ptr is the reference of an array or a structure stored in memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary mode.
The fread() function is used to read bytes form the file.

Syntax of fread() function

fread( ptr, int size, int n, FILE *fp );

The fread() function takes four arguments.


ptr : ptr is the reference of an array or a structure where data will be stored after reading.
size : size is the total number of bytes to be read from file.
n : n is number of times a record will be read.
FILE* : FILE* is a file where the records will be read.

// C program for writing a block of data involving structures to file


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

struct person
{
int id;
char fname[20];
char lname[20];
};

int main ()
{
FILE *outfile;

// open file for writing


outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opening file\n");

7
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

exit(1);
}

struct person input1 = {1, "royce", "anto"};


struct person input2 = {2, "rinil", "jose"};
//input1 and inut2 are structure variables
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);

if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");

// close file
fclose (outfile);
}
// C program for reading a block of data involving structure from a file
#include <stdio.h>
#include <stdlib.h>

// struct person with 3 fields


struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *infile;
struct person input;
// Open person.dat for reading
infile = fopen ("person.dat", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
// read file contents till end of file
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %s\n", input.id, input.fname, input.lname);

// close file
fclose (infile);
}
gcc demoread.c
./a.out
id = 1 name = royce anto
id = 2 name = rinil jose

8
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

Write a program to write and read the information about player containing players name, age and runs.
Use fread( ) and fwrite( ) functions?

#include<stdio.h>
#include<process.h>
struct record
{
int age;
int runs;
};
void main()
{
FILE *fp;
struct record emp;
fp=fopen(“record.dat”,”w”);
if(fp==NULL)
{
printf(“Cannot open file”);
exit(1);
}
printf(“Enter player name, age and runs scored”);
printf(“==============================”);
scanf(“%s %d %d”,emp.player, &emp.age,&emp.runs);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
if(fp=fopen(“record.dat”,”r”))==NULL)
{
printf(“error in opening file”);
exit(1);
}
printf(\n Record entered is\n”);
fread(&emp,sizeof(emp),1,fp);
printf(“%s %d %d”,emp.player, emp.age, emp.runs);
fclose(fp);
}

OUTPUT
Enter player name, age and runs scored
=============================
Arun 25 10000

Record entered is
Arun 25 10000

fseek() function
It is a file function used to position file pointer on the stream. Three arguments are passed through this
function:
 File pointer
 Negative or Positive number used to re-position file pointer towards backward or forward
direction.
 The current position of the file pointer

9
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation

C PROGRAM TO copy the contents of one file to another


#include <stdio.h>
#include <stdlib.h> // For exit()

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
printf(“%c”,c);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
HELLO WORLD
Contents copied to b.txt

13
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST

You might also like