100% found this document useful (1 vote)
22 views25 pages

File Pointer Usage in C Programming

Uploaded by

JUSTIN RAJ S
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
100% found this document useful (1 vote)
22 views25 pages

File Pointer Usage in C Programming

Uploaded by

JUSTIN RAJ S
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

FILES IN C

Introduction to Files
➢ A file is a collection of data stored on a secondary storage device
like hard disk.
➢ So far data was entered into the programs through the keyboard.
➢ So Files are used for storing information that can be processed by
the programs.
➢ Filles are not only used for storing the data, programs are also
stored in files.
Types of Files in C:

➢ A file can be classifitypes based on the way the file stores


the data. They are as follows:

•Text Files
•Binary Files
1. Text Files

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

2. Binary Files

➢ 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.
•More secure as they are not easily readable.
•They are generally stored with .bin file extension.
USING FILES IN C :

➢ To use files in C, We must follow the steps given below:

• declare a file pointer variable


• open the file
• process the file
• close the file
Declaring a File Pointer Variable:
➢ There can be a number of files on the disk. In order to access a
particular file, you must specify the name of the file that has to be
used.
➢ This is accomplished by using a file pointer variable that points to
a structure FILE (defined in stdio.h).
➢ The file pointer will then be used in all subsequent operations in
the file.
➢ The syntax for declaring a file pointer is
FILE *file_ pointer_name.
➢ For example, if we write FILE *fp; Then, fp is declared as a file
pointer.
Open a File in C

➢For opening a file in C, the fopen() function is used with the


filename or file path along with the required access modes.

Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);

Parameters
•file_name: name of the file when present in the same directory as the source file. Otherwise, full path.
•access_mode: Specifies for what operation the file is being opened.
Return Value
•If the file is opened successfully, returns a file pointer to it.
•If the file is not opened, then returns NULL.
File opening modes in C
➢ File opening modes or access modes specify the allowed
operations on the file to be opened.
➢ They are passed as an argument to the fopen() function.
➢ Some of the commonly used file access modes are listed
below:
Opening Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets
r up a pointer that points to the first character in it. If the file cannot be opened fopen( )
returns NULL.

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

Open for writing in text mode. If the file exists, its contents are overwritten. If the file
w
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

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

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets
a up a pointer that points to the last character in it. It opens only in the append mode. If
the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file does
ab
not exist, it will be created.
Opening Modes Description

Searches file. It is opened successfully fopen( ) loads it into memory and sets up a
r+
pointer that points to the first character in it. Returns NULL, if unable to open the file.

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

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
w+
file is created. Returns NULL, if unable to open the file.

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

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a pointer that points to the last character in it. It opens the file in both reading and
a+
append mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to
open the file.

Open for both reading and appending in binary mode. If the file does not exist, it will be
ab+
created.
Example of Opening a File
// C Program to illustrate file opening
#include <stdio.h> Output:
#include <stdlib.h> The file is not opened. The
program will now exit.
int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;

// opening the file in read mode


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

// checking if the file is opened successfully


if (fptr == NULL) {
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}

return 0;
}
Closing a File
➢ The fclose() function is used to close the file. After
successful file operations, you must always close a file to
remove it from the memory.
➢ Syntax of fclose()
fclose(file_pointer);

➢ Example:
FILE *fptr ;
fptr= fopen(“[Link]”, “w”);
---------- Some file Operations -------
fclose(fptr);
Reading From a File

➢ C provides the following set of functions to read data from a file.


▪ fscanf()
▪ fgets()
▪ fgetc()
▪ fread()
➢ fscanf() Example:
#include <stdio.h>
Reads formatted input from a file
int main() {
stream. FILE *file = fopen("[Link]", "r");
Points: int age;
char name[50];
•Used for reading data with specific
formats. if (file) {
fscanf(file, "%d %s", &age, name);
•Requires a format specifier (like printf("Age: %d, Name: %s\n", age, name);
%d, %s, etc.). fclose(file);
} else {
•Returns the number of items printf("Error opening file.\n");
}
successfully read. return 0;
SYNTAX: }
int fscanf(FILE *stream, const char *format,
OUTPUT:
...); Age: 25, Name: John
➢ Fgets(): EXAMPLE:
#include <stdio.h>
Reads a string from a file until a newline or
EOF is encountered. int main() {
FILE *file = fopen("[Link]", "r");
char buffer[100];
Points:
•Useful for reading an entire line of text. if (file) {
while (fgets(buffer, sizeof(buffer), file)) {
•Stops reading when it encounters a newline printf("Read line: %s", buffer);
or reaches the maximum number of }
characters. fclose(file);
} else {
•Includes the newline character in the output printf("Error opening file.\n");
(if it’s read). }
SYNTAX: return 0;
}
char *fgets(char *str, int n, FILE *stream);
OUTPUT:
Read line: Hello, World!
Read line: This is a test.
➢ fgetc(): EXAMPLE:
Reads a single character from a fil stream. #include <stdio.h>
Points:
int main() {
•Useful for reading one character at a time. FILE *file = fopen("[Link]", "r");
•Returns the character read or EOF if the end of int ch;

the file is reached. if (file) {


•Can be used to process files character by while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print each character to stdout
character. }
SYNTAX: fclose(file);
} else {
int fgetc(FILE *stream); printf("Error opening file.\n");
}
return 0;
}

OUTPUT:
ABC
123
➢ fread(): EXAMPLE:
#include <stdio.h>
Reads a block of data from a file
stream. int main() {
FILE *file = fopen("[Link]", "rb");
Points: int numbers[5];
•Ideal for reading binary data or arrays. if (file) {
•Takes the size of each element, size_t read_count = fread(numbers, sizeof(int), 5, file);
for (size_t i = 0; i < read_count; i++) {
number of elements, and the file printf("%d ", numbers[i]);
stream as arguments. }
printf("\n");
•Returns the number of items read fclose(file);
successfully. } else {
printf("Error opening file.\n");
SYNTAX: }
size_t fread(void *ptr, size_t size, size_t return 0;
}
count, FILE *stream); OUTPUT:
12345
➢ Write to a File:
• The file write operations can be performed by the functions fprintf()
and fputs() with similarities to read operations.
• C programming also provides some other functions that can be used
to write data to a file such as:
• fprintf()
• fputs ()
• fputc ()
• fwrite()
➢fprintf() EXAMPLE:
#include <stdio.h>
Writes formatted output to a file stream.
int main() {
Points: FILE *file = fopen("[Link]", "w");
•Similar to printf(), but outputs to a file. int age = 25;
•Supports format specifiers (like %d, %s, etc.). char name[] = "Alice";

•Returns the number of characters written. if (file) {


fprintf(file, "Age: %d, Name: %s\n", age,
SYNTAX: name);
int fprintf(FILE *stream, const char *format, ...); fclose(file);
} else {
printf("Error opening file.\n");
}
return 0;
}
OUTPUT:
Age: 25, Name: Alice
➢ fputs() EXAMPLE:
#include <stdio.h>
Writes a string to a file stream.
int main() {
Points: FILE *file = fopen("[Link]", "a"); // Append mode
•Writes a string but does not add a char message[] = "Hello, World!\n";

newline automatically. if (file) {


•Does not format the output like fputs(message, file);
fclose(file);
fprintf(). } else {
•Returns a non-negative number on }
printf("Error opening file.\n");

success or EOF on error. return 0;


}
Syntax: OUTPUT:
int fputs(const char *str, FILE *stream); Age: 25, Name: Alice
Hello, World!
EXAMPLE:
➢ fputc() #include <stdio.h>

Writes a single character to a file int main() {


stream. FILE *file = fopen("[Link]", "a"); // Append mode

Points: if (file) {
•Useful for writing one character at a fputc('A', file);
fputc('\n', file);
time. fclose(file);
•Returns the character written or EOF } else {
printf("Error opening file.\n");
on error. }
return 0;
•SYNTAX: }
int fputc(int character, FILE *stream); OUTPUT:
Age: 25, Name: Alice
Hello, World!
A
EXAMPLE:
fwrite() #include <stdio.h>
Writes a block of data to a file stream.
int main() {
Points: FILE *file = fopen("[Link]", "wb");
•Ideal for writing binary data or arrays. int numbers[] = {1, 2, 3, 4, 5};
•Takes the size of each element, number if (file) {
fwrite(numbers, sizeof(int), 5, file);
of elements, and the file stream as fclose(file);
arguments. } else {
•Returns the number of items written }
printf("Error opening file.\n");

successfully. return 0;
}
SYNTAX: OUTPUT:
size_t fwrite(const void *ptr, size_t size, size_t This file will contain binary data representing the integers
count, FILE *stream); 1,2,3,4,5. (It's not human-readable; you would need a hex
viewer to see the actual bytes.)
EXAMPLE:
Program to create a file, write in it and close the file:
// C program to Open a File,
// Write in it, And Close the File
#include <stdio.h>
#include <string.h>

int main()
{

// Declare the file pointer


FILE* filePointer;

// Get the data to be written in file


char dataToBeWritten[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()


// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w");
// Check if this filePointer is null OUTPUT:
// which maybe if the file does not exist
if (filePointer == NULL) {
The file is now opened. Data
printf("GfgTest.c file failed to open."); successfully written in file GfgTest.c The
} file is now closed.
else {

printf("The file is now opened.\n");

// Write the dataToBeWritten into the file


if (strlen(dataToBeWritten) > 0) {

// writing in the file using fputs()


fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}

// Closing the file using fclose()


fclose(filePointer);

printf("Data successfully written in file "


"GfgTest.c\n");
printf("The file is now closed.");
}

return 0;
}
THANK YOU

You might also like