0% found this document useful (0 votes)
19 views17 pages

C File Operations and Types Explained

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)
19 views17 pages

C File Operations and Types Explained

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

5.

FILES
Why files are needed?
When program is terminated, the data is stored in memory is lost. Storing data in a file even if
the program is terminated the data will be safe.
To enter large amount of data, it will take a lot of time to enter them all. If you have a file
containing all the data, you can easily access the content of the file using few commands in c.
If you store the data in a file it can easily move data from one computer to another without any
changes.
What is a file?
A File is a Sequence of bytes or sequence of memory, where we can save data permanently
(Hard disk)
(or)
A File is a collection of data stored in the secondary memory.
Types of files : There are two types of file in c language.
1. Text file
2. Binary file
1. Text file:
A text file contains data in the form of ASCII characters and is generally used to store a stream of
characters. Each line in a text file ends with a new line character (‘\n’). It can be read or written
by any text editor. They are generally stored with .txt file extension. Text files can also be used to
store the source code. It is a Human understandable file.
2. Binary file:
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
The binary files can be created only from within a program and their contents can only be
read by a program. It is more secure as they are not easily readable.
They are generally stored with .bin file extension. It is not understandable to the human. It is
machine friendly language.
They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
C File Operations:
There are 5 major operations can be performs on c files
1. Creating a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Closing a file

Prepared By K. VENU Page 1


Declaring a file pointer to a file:
A file pointer is a variable that is used to refer to an opened file in a C program. The file pointer
is actually a structure that stores the file data such as the file name, its location, mode, and the
current position in the file. It is used in almost all the file operations in C such as opening,
closing, reading, writing, etc. A file pointer is a pointer to a structure of type FILE.
Syntax: FILE *file pointer;
Ex: [Link] *fp;
2. FILE *a;
File opening in various modes: To perform any I/O operation on a file it must be open, to open
a file in c fopen() function is used.
Syntax: FILE *fopen(const char *filename, const char *mode);

read write append


filename: A string that represents the name of the file to be opened. It can contain the full
path or just the file name if the file is in the current directory.
mode: A string that specifies the mode in which the file should be opened. The mode can be
read, write, append, etc.
return Value:
If the file is successfully opened, the fopen() function returns a pointer to the file.
If the file cannot be opened (for example, if the file does not exist or cannot be found), the
function returns a NULL pointer.

File Opening modes in standard I/O:

Prepared By K. VENU Page 2


Ex: FILE *fp;
fp=fopen(“[Link]”,”w”);
fp=fopen(“[Link]”,”r”);
fp=fopen(“[Link]”,”a”);
fp=fopen(“[Link]”,”w+”);
fp=fopen(“[Link]”,”r+”);
fp=fopen(“[Link]”,”a+”);
1. "r" ( Read mode):
This mode opens an existing file only for reading data; if the file does not exist, fopen() returns
NULL. You cannot write or modify the file in this mode.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
if (fp == NULL)
{
printf("File does not exist\n");
return 1;
}
printf("File contents:\n");
while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
}
fclose(fp);
return 0; }

Prepared By K. VENU Page 3


2. "w" ( write mode):
This mode opens a file for writing. If the file already exists, its contents are erased, and if it
does not exist, a new file is created. You can only write data in this mode.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("[Link]", "w");
if (fp == NULL)
{
printf("File cannot be opened\n");
return 1;
}
fprintf(fp, "This file is created using w mode");
fclose(fp);
printf("Data written successfully\n");
return 0;
}
3. "a" ( Append mode):
This mode opens a file for writing at the end of the file; existing data is preserved, and new data
is added at the end. If the file does not exist, it is created.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("[Link]", "a");
if (fp == NULL)

Prepared By K. VENU Page 4


{
printf("File cannot be opened\n");
return 1;
}
fprintf(fp, "\nThis line is appended");
fclose(fp);
printf("Data appended successfully\n");
return 0;
}
4. "r+" ( Read and Write mode):
This mode opens an existing file for both reading and writing; the file must already exist, and
writing can be done anywhere in the file.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "r+");
if (fp == NULL)
{
printf("File does not exist\n");
return 1;
}
fprintf(fp, "Hi "); // writes at beginning
rewind(fp); // move pointer to start
printf("File contents:\n");
while ((ch = fgetc(fp)) != EOF)
{

Prepared By K. VENU Page 5


printf("%c", ch);
}
fclose(fp);
return 0;
}
5. "w+" ( Read and Write mode):
This mode opens a file for both reading and writing; if the file exists, its contents are erased,
and if it does not exist, a new file is created.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "w+");
if (fp == NULL)
{
printf("File cannot be opened\n");
return 1;
}
fprintf(fp, "File opened using w+ mode");
rewind(fp);
printf("File contents:\n");
while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
}
fclose(fp);
return 0; }

Prepared By K. VENU Page 6


6. "a+" (Read and Append mode):
This mode opens a file for both reading and writing; reading can be done anywhere, but writing
always occurs at the end of the file. The file is created if it does not exist.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "a+");
if (fp == NULL)
{
printf("File cannot be opened\n");
return 1;
}
fprintf(fp, "\nAppended using a+ mode");
rewind(fp);
printf("File contents:\n");
while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
}
fclose(fp);
return 0;
}
File closing :

After performing read/write operations the file must be closed to remove the file from the
Memory.
To close a file, fclose() function is used.
fclose() returns 0 on success and -1 on error.

Prepared By K. VENU Page 7


Syntax: int fclose(FILE *file pointer name);
Ex: fclose(fp);

Input/output operations on a file:


It means performing a read/write operations on a file, here reading means getting the Data
from file(output operation) and writing data into a file (input operation).
Reading from a File:
The file read operation in C can be performed using below functions are used.

Function Description

fscanf() Use formatted string and variable arguments list to


take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

getw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

1. fscanf()
fscanf() is used to read formatted data (like integers, floats, strings) from a file, just like scanf()
reads from the keyboard.
Syntax: fscanf(FILE *fp, "format", &var1, &var2);
Example:
#include <stdio.h>
int main() {
FILE *fp;
int num;
fp = fopen("[Link]", "r");

Prepared By K. VENU Page 8


fscanf(fp, "%d", &num);
printf("Number = %d", num);
fclose(fp);
return 0;
}

[Link](): fgets() reads a line of text (string) from a file until a newline or specified size is
reached.

Syntax: fgets(char *str, int size, FILE *fp);

Example:

#include <stdio.h>

int main() {

FILE *fp;

char str[50];

fp = fopen("[Link]", "r");

fgets(str, 50, fp);

printf("%s", str);

fclose(fp);

return 0;

[Link](): fgetc() reads one character at a time from a file.

Syntax: int fgetc(FILE *fp);

Example:

#include <stdio.h>

int main() {
Prepared By K. VENU Page 9
FILE *fp;

char ch;

fp = fopen("[Link]", "r");

while ((ch = fgetc(fp)) != EOF) {

printf("%c", ch);

fclose(fp);

return 0;

4. fread(): fread() is used to read binary data (blocks of data) from a file.

Syntax: fread(void *ptr, size_t size, size_t count, FILE *fp);

Example:

#include <stdio.h>

int main() {

FILE *fp;

int num;

fp = fopen("[Link]", "rb");

fread(&num, sizeof(int), 1, fp);

printf("Number = %d", num);

fclose(fp);

return 0;

Prepared By K. VENU Page 10


Write to a File: The file write operations can be performed by the below functions.

Function Description

Similar to printf(), this function use formatted


fprintf() string and varible arguments list to print output
to the file.

fputs() Prints the whole line in the file and a newline at


the end.

fputc() Prints a single character into the file.

putw() Prints a number to the file.

fwrite() This function writes the specified amount of


bytes to the binary file.

[Link](): fprintf() is a formatted output function used to write formatted data (such as
integers, floats, characters, and strings) to a file, similar to how printf() writes to the screen; it
allows the use of format specifiers like %d, %f, and %s to control how data is written into the
file.
Syntax: fprintf(FILE *fp, "format", variables);
Example:

#include <stdio.h>
int main()
{
FILE *fp;
int a = 10;
fp = fopen("[Link]", "w");
fprintf(fp, "Value of a = %d", a);

fclose(fp);

return 0;

Prepared By K. VENU Page 11


2. fputs(): Writes a string to a file.

Syntax: fputs(string, FILE *fp);

Example:

#include <stdio.h>

int main()

FILE *fp;

fp = fopen("[Link]", "w");

fputs("Hello World", fp);

fclose(fp);

return 0;

3. fputc(): fputs() is used to write a string to a file; it writes characters from the given string to
the file until the null character ('\0') is encountered, but it does not automatically add a newline
unless it is included in the [Link]: fputc(character, FILE *fp);
Example :

#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("[Link]", "w");

fputc('A', fp);

fclose(fp);

return 0;

Prepared By K. VENU Page 12


4. fwrite(): fwrite() is used to write blocks of binary data to a file; it writes a specified number of
elements of a given size from a memory buffer to a file, making it efficient for writing structures
or arrays in binary form.

Syntax: fwrite(buffer, size, count, FILE *fp);

Example:

#include <stdio.h>

int main()

FILE *fp;
int arr[3] = {10, 20, 30};
fp = fopen("[Link]", "wb");
fwrite(arr, sizeof(int), 3, fp);
fclose(fp);
return 0;
}
Note:
Sequential access file: In C, a sequential access file is a file where data is read or written one
after another in order, starting from the beginning and going to the end, just like reading a
book page by page.
you cannot jump directly to the middle of the file, and functions like fgetc(), fgets(), fscanf(),
fputc(), fputs(), and fprintf() are used to handle data in sequence.
These make this type of file easy to use and good for simple text files, but slow when you want
to find or change a specific piece of data.

Random file access: Random access to a file allows programmer to read or write data at any
position within a File.
The c language supports below functions:

1. ftell()
2. rewind()
3. fseek()

[Link](): ftell in C is used to find out the position of the file pointer in the file with respect to
starting of the file.
Syntax : long ftell(FILE *stream);
Ex: num=ftell(fp);
Example:
#include <stdio.h>

Prepared By K. VENU Page 13


int main()
{
FILE *fp;
int pos;

fp = fopen("[Link]", "r");

if (fp == NULL)
{
printf("File not found");
return 1;
}
fgetc(fp); // read 1 character
fgetc(fp); // read another character
pos = ftell(fp);
printf("Current position of file pointer = %d", pos);
fclose(fp);
return 0;
}
Output:
Current position of file pointer = 2

[Link](): To set the position indicator to the beginning of the file, use the function rewind().
Syntax: void rewind(FILE *fp);
Ex: rewind (fp);
Example:
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
if (fp == NULL)
{
printf("File not found");
return 1;

Prepared By K. VENU Page 14


}
ch = fgetc(fp);
printf("First character: %c\n", ch);
rewind(fp); // move pointer to beginning
ch = fgetc(fp);
printf("After rewind, first character again: %c", ch);
fclose(fp);
return 0;
}
Output:
First character: H
After rewind, first character again: H
3. fseek(): It is used for file positioning within a stream. It allows to move the file pointer to a
Specific position within a file.
Syntax: int fseek(FILE *file pointer, long int offset, int position);
fseek() Reference Positions:
In C, fseek() reference positions are used to tell the compiler from where the file pointer should
move. A file is like a long sequence of bytes, and fseek() needs a starting point (reference
position) to correctly move the file pointer to the desired location.
The three reference positions used with fseek() are:
1. SEEK_SET
2. SEEK_CUR
3. SEEK_END

1. SEEK_SET (Beginning of the file): SEEK_SET moves the file pointer from the start of the file.
The offset value tells how many bytes to move forward from the beginning.
This is used when you want to read or write data from a fixed position in the file.
Example:

fseek(fp, 0, SEEK_SET); // Moves pointer to the beginning

fseek(fp, 10, SEEK_SET); // Moves pointer 10 bytes from start

Prepared By K. VENU Page 15


2. SEEK_CUR (Current position of the file pointer):
SEEK_CUR moves the file pointer relative to its current position. The offset can be positive
(move forward) or negative (move backward). This is useful when you want to skip or re-read
some data while processing a file.
Example:
fseek(fp, 5, SEEK_CUR); // Moves pointer 5 bytes forward
fseek(fp, -3, SEEK_CUR); // Moves pointer 3 bytes backward
3. SEEK_END (End of the file): SEEK_END moves the file pointer relative to the end of the file.
Usually, an offset of 0 places the pointer exactly at the end.
This is commonly used to find file size or to append/read data from the end of a file.
Example:
fseek(fp, 0, SEEK_END); // Moves pointer to end of file

fseek(fp, -10, SEEK_END);// Moves pointer 10 bytes before end

example:

#include <stdio.h>

int main()

FILE *fp;

char ch;

// Open file in write mode

fp = fopen("[Link]", "w+");

if (fp == NULL)

printf("File cannot be opened\n");

return 1;

// Write some text into the file

fputs("ABCDEFGHIJ", fp); // 10 characters

/* -------- SEEK_SET -------- */

Prepared By K. VENU Page 16


fseek(fp, 0, SEEK_SET); // Move pointer to beginning

ch = fgetc(fp);

printf("After SEEK_SET, character read: %c\n", ch);

/* -------- SEEK_CUR -------- */

fseek(fp, 4, SEEK_CUR); // Move pointer 4 bytes forward

ch = fgetc(fp);

printf("After SEEK_CUR, character read: %c\n", ch);

/* -------- SEEK_END -------- */

fseek(fp, -1, SEEK_END); // Move pointer 1 byte before end

ch = fgetc(fp);

printf("After SEEK_END, character read: %c\n", ch);

fclose(fp);

return 0;

Output:

After SEEK_SET, character read: A

After SEEK_CUR, character read: F

After SEEK_END, character read: J

Prepared By K. VENU Page 17

You might also like