Introduction to Files in C
Introduction to Files in C
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 a 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. 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.
File Operations
In C, you can perform four major operations on files, either text or
binary:
3. Closing a file
ptr = fopen("fileopen","mode");
For example,
fopen("E:\\cprogram\\
newprogram.txt","w");
Let's suppose the file newprogram.txt doesn't exist in the location E:\
cprogram. The first function creates a new file
named newprogram.txt and opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents
of the file.
Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram. The second function opens the existing file for
reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write
into the file.
The reading mode only allows you to read the file, you cannot write
into the file.
Open for reading in binary If the file does not exist, fopen()
rb
mode. returns NULL.
the file.
Open for both reading and If the file does not exist, fopen()
r+
writing. returns NULL.
Open for both reading and If the file does not exist, fopen()
rb+
writing in binary mode. returns NULL.
Open for both reading and If the file does not exist, it will be
a+
appending. created.
Open for both reading and If the file does not exist, it will be
ab+
appending in binary mode. created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
fclose(fptr);
They are just the file versions of printf() and scanf() . The only
difference is that fprintf() and fscanf() expects a pointer to the
structure FILE.
int main()
{
char num;
FILE *fptr;
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%c",num);
fclose(fptr);
return 0;
}
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
This program reads the integer present in the program.txt file and
prints it onto the screen.
If you successfully 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 a similar
way.
fwrite(addressData, sizeData,
numbersData, pointerToFile);
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
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.
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
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()
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.
seek() in C
When dealing with files containing multiple records, locating a specific record can be
cumbersome and inefficient if we have to traverse through all the preceding records.
This not only consumes memory but also increases operational time. To address this,
we can utilize fseek() which efficiently positions the file cursor to the desired record.
Parameters
Example of fseek()
#include <stdio.h>
int main() {
FILE* filePtr;
filePtr = fopen("data.bin",
"rb");
fclose(filePtr);
return 0;
}
In this instance, we initiate the opening of a binary file named "data.bin" for reading in
binary mode ("rb"). We then use fseek() to move the file pointer to the end of the file
(SEEK_END). Finally, we print the position of the file pointer using ftell(), which will
indicate the size of the file in bytes.
rewind() in C
The rewind() function in C is utilized to move the file pointer back to the beginning of
the file. It serves as a convenient alternative to fseek() when the intention is to position
the file pointer at the start of the file.
Syntax of rewind()
Example
#include <stdio.h>
int main() {
FILE* filePtr;
filePtr = fopen("data.txt", "w+");
// Write some content to the file
fprintf(filePtr, "Hello, World!\
n");
// Reposition the file pointer to
the start of the file.
rewind(filePtr);
// Read from the file
char buffer[50];
fscanf(filePtr, "%[^\n]", buffer);
// Print the content read from the
file
printf("%s\n", buffer);
// Close the file
fclose(filePtr);
return 0;
}
In this example, we open a file named "data.txt" in write mode with reading capabilities
("w+"). We write the string "Hello, World!\n" to the file using fprintf(). Then, we
use rewind() to reset the file pointer to the beginning of the file. Next, we read the
content of the file using fscanf(), storing it in the buffer array, and finally, we print the
content read from the file.
Whence Meaning
SEEK_CUR Starts the offset from the current location of the cursor in the file.
puts the file pointer to the fseek(FILE *stream, long int offset,
fseek()
specified place int whence)
the file
C Preprocessor Directives
Last Updated : 19 Jul, 2024
int main()
{
// Using the PI macro to calculate
double radius = 8.0;
double area = PI * radius * radius;
return 0;
}
Output
int main()
{
// Using standard input/output
functions from stdio.h
printf("Hello, Geek!\n");
Output
Hello, Geek!
Sum: 15
3. #if, #ifdef, #else, #elif, #endif – Conditional Compilation
Conditional Compilation directives help to compile a specific portion
of the program or let us skip compilation of some specific part of the
program based on some conditions