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

C Programming Files I

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C Programming Files I

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

C Programming Files I/O

There are a large number of functions to handle file I/O (Input Output) in C. In this
tutorial, you will learn to handle standard I/O in C using fprintf(), fscanf(), fread(),
fwrite(), fseek and more.

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

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 that you can easily create using Notepad or any simple
text editors.

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 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 higher amount of data, are not readable easily and provides a better
security than text files.

File Operations
In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Working with files


When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.

FILE *fptr;

Opening a file - for creation and edit


Opening a file is performed using the library function in the "stdio.h" header file:
fopen().

The syntax for opening a file in standard I/O is:


ptr = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

If the file does not exist, fopen() returns


r Open for reading.
NULL.

If the file does not exist, fopen() returns


rb Open for reading in binary mode.
NULL.

If the file exists, its contents are overwritten. If


w Open for writing.
the file does not exist, it will be created.

If the file exists, its contents are overwritten. If


wb Open for writing in binary mode.
the file does not exist, it will be created.

Open for append. i.e, Data is


a If the file does not exists, it will be created.
added to end of file.
Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

Open for append in binary mode.


ab If the file does not exists, it will be created.
i.e, Data is added to end of file.

If the file does not exist, fopen() returns


r+ Open for both reading and writing.
NULL.

Open for both reading and writing If the file does not exist, fopen() returns
rb+
in binary mode. NULL.

If the file exists, its contents are overwritten. If


w+ Open for both reading and writing.
the file does not exist, it will be created.

Open for both reading and writing If the file exists, its contents are overwritten. If
wb+
in binary mode. the file does not exist, it will be created.

Open for both reading and


a+ If the file does not exists, it will be created.
appending.

Open for both reading and


ab+ If the file does not exists, it will be created.
appending in binary mode.

Closing a File
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be


closed.

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() andfscanf().

They are just the file versions of printf() and scanf(). The only difference is that, fprint
and fscanf expects a pointer to the structure FILE.

Writing to a text file


Example 1: Write to a text file using fprintf()

#include <stdio.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);

return 0;
}

Reading from a text file


Example 2: Read from a text file using fscanf()

#include <stdio.h>
int main()
{
int num;
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);

return 0;
}
This program reads the integer present in the program.txt file and prints it onto the
screen.

If you succesfully created the file from Example 1, running this program will get you the
integer you entered.

Other functions like fgetchar(), fputc() etc. can be used in similar way.

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.

Writing to a binary file


To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk,
number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);

Example 3: Writing to a binary file using fwrite()

#include <stdio.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.


exit(1);
}

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


{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, *fptr);
}
fclose(fptr);

return 0;
}

Reading from a binary file


Function fread() also take 4 arguments similar to fwrite() function as above.

fread(address_data,size_data,numbers_data,pointer_to_file);

Example 4: Reading from a binary file using fread()


#include <stdio.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);

return 0;
}
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.

Syntax of fseek()
fseek(FILE * stream, long int 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

SEKK_SET Starts the offset from the beginning of the file.

SEKK_END Starts the offset from the end of the file.

Starts the offset from the current location of the cursor in the
SEKK_CUR
file.
Example of fseek()
#include <stdio.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);
}

// Moves the cursor to the end of the file


fseek(fptr, sizeof(struct threeNum), SEEK_END);

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);
return 0;
}

This program will start reading the records from the file program.bin in the reverse order (last to
first) and prints it.

1. Write a C program to read name and marks of n number of students from user
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);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);

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


}

fclose(fptr);
return 0;
}

2. Write a C program to read name and marks of n number of students from user
and store them in a file. If the file previously exits, add the information of n
students.

#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;
}

3. Write a C program to write all the members of an array of strcures to a file


using fwrite(). Read the array from the file and display on the screen.

#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;

fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);

printf("Enter height: ");


scanf("%d", &stud1[i].height);
}

fwrite(stud1, sizeof(stud1), 1, fptr);


fclose(fptr);

fptr = fopen("file.txt", "rb");


fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}

You might also like