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

Introduction to Files in C

Files are essential for data preservation after program termination, efficient data entry, and easy data transfer between computers. There are two main types of files: text files, which are human-readable but less secure, and binary files, which are more secure and can hold larger amounts of data. In C, file operations include creating, opening, closing, reading, and writing to files, with specific functions and modes for handling both text and binary files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Introduction to Files in C

Files are essential for data preservation after program termination, efficient data entry, and easy data transfer between computers. There are two main types of files: text files, which are human-readable but less secure, and binary files, which are more secure and can hold larger amounts of data. In C, file operations include creating, opening, closing, reading, and writing to files, with specific functions and modes for handling both text and binary files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

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 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:

1. Creating a new file

2. Opening an existing file

3. Closing a file

4. Reading from and writing information to a file

To use a file four essential actions should be carried out. These


are,

a. Declare a file pointer variable.

b. Open a file using the fopen() function.

c. Process the file using suitable functions.

d. Close the file using the fclose() and fflush() functions.

Declaration of file pointer: A pointer variable is used to points a structure


FILE.

FILE *file_pointer_name; Eg : FILE *fp

Opening a file To open a file using the fopen() function.

Its syntax is,

FILE *fopen(const char *fname,const char* mode);

const char *fname represents the file name.

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

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.

Opening Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file

If the file does not exist, fopen()


r Open for reading.
returns NULL.

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

If the file exists, its contents are


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

If the file exists, its contents are


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

a Open for append. If the file does not exist, it will be


Data is added to the end of created.
Opening Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file

the file.

Open for append in binary


mode. If the file does not exist, it will be
ab
Data is added to the end of created.
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.

If the file exists, its contents are


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

If the file exists, its contents are


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

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.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file


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

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.

Example 1: Write to a text file


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

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

// use appropriate location if you are using MacOS or


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

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

printf("Enter num: ");


scanf("%c",&num);

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

return 0;
}

Reading and writing to a text file


For reading and writing to a text file, we use the
functions fprintf() and fscanf().
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.
#include <stdlib.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 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.

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 fwrite() function. The
functions take four arguments:
1. address of data to be written in the disk

2. size of data to be written in the disk

3. number of such type of data

4. pointer to the file where you want to write.

fwrite(addressData, sizeData,
numbersData, pointerToFile);

Example 3: 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.


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

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 4: Read from a binary file using fread()


#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","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\n", num.n1, num.n2,
num.n3);
}
fclose(fptr);
return 0;
}
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 3.

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.
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.

Syntax for fseek()


fseek(FILE *file_ptr,
int

long int offset, int pos );

Parameters

 file_ptr: Pointer to the file stream.


 offset: Number of bytes to offset from the position
specified by pos.
 pos: Position from where the offset is applied. It can take
one of the following values:
o SEEK_SET: Beginning of the file.
o SEEK_CUR: Current position of the file pointer.
o SEEK_END: End of the file.

Example of fseek()

#include <stdio.h>

int main() {
FILE* filePtr;
filePtr = fopen("data.bin",
"rb");

// Move the file pointer to the


end of the file
fseek(filePtr, 0, SEEK_END);

// Print the position of the


file pointer
printf("Position of file
pointer: %ld\n", ftell(filePtr));

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()

void rewind(FILE *file_pointer);

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.

Different whence in fseek()

Whence Meaning

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.

More Functions for C File Operations


Function Description Syntax

Used to open an existing file FILE *fopen(“file_name”,


fopen()
or to create a new file “mode”);

Used to write data in existing fprintf(FILE *stream, const char


fprintf()
file *format [, argument, ...])

Used to read data from the fscanf(FILE *stream, const char


fscanf()
file *format [, argument, ...])

Used to write characters in a


fputc() fputc(int c, FILE *stream)
file

Used to read characters from


fgetc() fgetc(FILE *stream)
a file

fclose() Used to close existing file fclose( FILE *fp )

puts the file pointer to the fseek(FILE *stream, long int offset,
fseek()
specified place int whence)

Used to write integral value in


fputw() fputw(int number,File *fp)
the file

Used to read integral value


fgetw() fgetw(File *fp)
from the file

ftell() It will return the current ftell(FILE *stream)


position of the file pointer in
Function Description Syntax

the file

the file pointer is set to the


rewind() rewind(FILE *stream)
start of the file

C Preprocessor Directives
Last Updated : 19 Jul, 2024



In almost every C program we come across, we see a few


lines at the top of

the program preceded by a hash (#) sign. They are called


preprocessor directives and are preprocessed by the
preprocessor before actual compilation begins. The end of
these lines is identified by the newline character ‘\n’, no
semicolon ‘;’ is needed to terminate these lines.

Preprocessor directives are mostly used in defining macros,


evaluating conditional statements, source file inclusion,
pragma directives, line control, error detection, etc.
List of Preprocessor Directives in C
The following table lists all the preprocessor directives
available in the C programming language:
Preprocessor Directives
Description

Used to define a macro.


#define
Used to undefine a macro.
#undef
Used to include a file in the source
#include code program.

Used to include a section of code if a


#ifdef certain macro is defined by #define.
Preprocessor Directives
Description

Used to include a section of code if a


certain macro is not defined by
#ifndef #define.

Check for the specified condition.


#if
Alternate code that executes when #if
#else fails.

Used to mark the end of #if, #ifdef,


#endif and #ifndef.

Used to generate a compilation error


#error message.

Used to modify line number and


#line filename information.

To make sure the header is included


#pragma once only once.

Used for displaying a message during


#pragma message compilation.

Types of Preprocessor Directives in C


In C, preprocessor directives are categorized based on their
functionalities following are the types of preprocessor
directives:
1. Macro Definition
2. File Inclusion directive
3. Conditional Compilation
4. Line control
5. Error directive
6. Pragma direcive
Let us now have a look at each one of these directives in
detail:
1. #define – Macro Directive
In C, macro definition directives uses the #define preprocessor
directive to define the macros and symbolic constants. We
use #define directive to define macro. Macro are basically the
symbolic names that represents lines of code or some values.
This directive is used to create constants or to define short,
reusable codes.
Syntax
#define token value
Example
// C program to illustrate the use of
#define directive
#include <stdio.h>

// Defining a macro for PI


#define PI 3.14159

int main()
{
// Using the PI macro to calculate
double radius = 8.0;
double area = PI * radius * radius;

// Displaying the calculated area


printf("Area of the circle is: %f\n",
area);

return 0;
}

Output

Area of the circle is: 201.061760


2. #include – File Inclusion Directive
#include is one of the file inclusion directive in C. #include
preprocessor directive is used to include the content of one file to
another file i.e. source code during the preprocessing stage. This is
done to easily organize the code and increase the reusability of code.
Syntax
#include <file_name>
or
#include "filename"
Here, file inclusion with double quotes ( ” ” ) tells the compiler to
search for the header file in the directory of source file.
Example
The below example demonstrates the use of file inclusion directive
#include.
// C program to demonstrate the use of file inclusion
// directive #include.

#include <stdio.h> // includng header


file for Standard input/output
functions
#include <stdlib.h> // includng header
file for Standard library functions

int main()
{
// Using standard input/output
functions from stdio.h
printf("Hello, Geek!\n");

// Using standard library functions


int num1 = 10, num2 = 5;
int sum = num1 + num2;

// displayng the result using


printf from stdio.h
printf("Sum: %d\n", sum);
return 0;
}

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

#ifdef:. The controlled text inside a conditional will embrace


preprocessing directives. They are executed only if the conditional
succeeds. You can nest these in multiple layers, but they must be
completely nested. In other words, ‘#endif’ always matches the
nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a
conditional group in one file and finish it in another.
Syntax
#ifdef MACRO
controlled text
#endif

#ifndef: In #ifdef directive if the macroname is defined, then the block


of statements after the #ifdef directive will be executed normally but in
case it is not defined, the compiler will simply skip this block of
statements. The #ifndef directive is simply the opposite of #ifdef
directive. In case of #ifndef , the block of statements between #ifndef
and #endif will get executed only if the macro or the identifier with
#ifndef is not defined.
Syntax
ifndef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
endif
else the lines after #else directive will be executed.
Syntax
#if macro_condition
statements
#elif macro_condition
statements
#else
statements
#endif

You might also like