What is file pointer in C language - How to use string in file handling in C language - fread() and fwrite() in C language - Direct access file in C language
What is file pointer in C language?
In C language, a file pointer is a special variable that is
used to keep track of the position of the next character to be read or written
in a file. It acts as an indicator or reference to the current position within the
file. File pointers are an integral part of file handling in C and are used in
conjunction with various file-related functions to perform operations on files.
The FILE type is a structure defined in the <stdio.h>
(standard input/output) library, and a file pointer is a variable of this type.
It is typically declared as a pointer to a FILE structure, and it holds
information about the file, such as its name, mode, and the current position of
the file pointer.
Here's a basic example of how to declare and use a file
pointer in C:
#include <stdio.h>
int main() {
FILE
*filePointer; // Declare a file pointer
// Open a file for
reading
filePointer =
fopen("example.txt", "r");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Perform file
operations using filePointer
// Close the file
when done
fclose(filePointer);
return 0; // Exit the program successfully
}
In this example:
filePointer is declared as a file pointer variable.
The fopen() function is used to open a file for reading, and
the file pointer is assigned the address of the opened file.
File operations can be performed using various functions
like fread(), fwrite(), fscanf(), etc., with filePointer as an argument.
The fclose() function is used to close the file when done.
The file pointer is essential for tracking the current
position within the file, and it gets updated automatically as data is read
from or written to the file. Functions like fseek() can be used to explicitly
move the file pointer to a specific position within the file.
In summary, a file pointer in C is a variable of type FILE*
that is used to manage and manipulate files by keeping track of the current
position and other relevant information about the file being accessed.
How to use string in file handling in C language
In C language, string handling in file operations involves
reading and writing strings to and from files. The standard input/output
library (<stdio.h>) provides functions that are commonly used for
string-based file handling. Here's a basic overview of how to use strings in
file handling:
Writing Strings to a File:
To write a string to a file, you can use functions like
fputs() or fprintf().
#include <stdio.h>
int main() {
FILE *filePointer;
// Open a file for
writing
filePointer =
fopen("output.txt", "w");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Write a string
to the file using fputs()
char myString[] =
"Hello, World!";
fputs(myString,
filePointer);
// Close the file
fclose(filePointer);
return 0;
}
Reading Strings from a File:
To read a string from a file, you can use functions like
fgets() or fscanf().
#include <stdio.h>
int main() {
FILE *filePointer;
char
buffer[100]; // Buffer to store the read
string
// Open a file for
reading
filePointer =
fopen("input.txt", "r");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Read a string
from the file using fgets()
fgets(buffer,
sizeof(buffer), filePointer);
// Display the
read string
printf("String read from file: %s", buffer);
// Close the file
fclose(filePointer);
return 0;
}
Using fprintf() and fscanf() for Formatted I/O:
You can use fprintf() and fscanf() for formatted
input/output with strings.
#include <stdio.h>
int main() {
FILE *filePointer;
// Open a file for
writing
filePointer =
fopen("formatted_output.txt", "w");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Write a
formatted string to the file using fprintf()
fprintf(filePointer, "Formatted Output: %s %d\n",
"Hello", 123);
// Close the file
fclose(filePointer);
// Open the file
for reading
filePointer =
fopen("formatted_output.txt", "r");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Read a
formatted string from the file using fscanf()
char str[50];
int num;
fscanf(filePointer, "%s %d", str, &num);
// Display the
read values
printf("Formatted Input: %s %d\n", str, num);
// Close the file
fclose(filePointer);
return 0;
}
Make sure to handle errors properly, check for successful file openings, and close the file when done to avoid potential issues. Adjust the file names, modes, and other parameters based on your specific requirements.
Flushing a stream using fread() and fwrite() in C language
fread() and fwrite() functions in C are used for reading
from and writing to files, respectively. However, the term "flushing a
stream" is typically associated with output streams rather than input
streams. Flushing refers to the act of making sure that any buffered data is
physically written to the file or output device.
For input streams, like when using fread(), there's
generally no concept of flushing because reading data from a file does not
involve buffering in the same way that writing data to a file does. The fread()
function reads a specified number of items from a file directly into memory
without buffering the data.
On the other hand, for output streams, flushing is relevant
when you want to ensure that any buffered data is written to the file or output
device. This is often necessary when working with interactive or line-buffered
output.
If you're working with fwrite() to write data to a file,
flushing might not be explicitly needed because fwrite() generally writes
directly to the file without buffering. However, if you are working with a
buffered output stream (e.g., stdout), you might need to use fflush() to ensure
that the data is immediately written to the output device.
Here's an example illustrating the use of fwrite() and
fflush():
#include <stdio.h>
int main() {
FILE *filePointer;
// Open a file for
writing
filePointer =
fopen("output.txt", "w");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Write data to
the file using fwrite()
char data[] =
"This is some data.";
fwrite(data, sizeof(char), sizeof(data) - 1, filePointer); // sizeof(data) - 1 to exclude the null terminator
// Flush the
output stream to ensure the data is written immediately
fflush(filePointer);
// Close the file
fclose(filePointer);
return 0;
}
In this example, fflush(filePointer) is used to ensure that
any buffered data is written to the file before closing it.
Remember that using fflush() is typically necessary when
working with buffered output streams, and it might not be relevant for every
file or output scenario. Always consider the specific requirements of your
program.
Direct access file in C language
In C language, direct access or random access file handling
involves the ability to read and write data to a file at any position, rather
than sequentially from the beginning to the end. The functions fseek() and
ftell() are commonly used for positioning the file pointer to a specific
location within the file. The file is then read or written from that position.
This capability is particularly useful when working with large files or when
specific data needs to be accessed without reading the entire file
sequentially.
Here's an example of using direct access file handling in C:
#include <stdio.h>
struct Student {
char name[50];
int rollNumber;
};
int main() {
FILE *filePointer;
// Open a binary
file for reading and writing
filePointer =
fopen("students.dat", "rb+");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Move the file
pointer to the end of the file
fseek(filePointer,
0, SEEK_END);
// Determine the
total number of records in the file
long totalRecords
= ftell(filePointer) / sizeof(struct Student);
// Example:
Writing a new student record at the end of the file
struct Student
newStudent;
printf("Enter
student name: ");
fgets(newStudent.name, sizeof(newStudent.name), stdin);
printf("Enter
roll number: ");
scanf("%d", &newStudent.rollNumber);
// Write the new
student record at the end of the file
fwrite(&newStudent, sizeof(struct Student), 1, filePointer);
// Move the file
pointer to the beginning of the file
fseek(filePointer,
0, SEEK_SET);
// Example:
Reading and displaying all student records
for (long i = 0; i
< totalRecords; i++) {
struct Student
student;
// Read a
student record from the file
fread(&student, sizeof(struct Student), 1, filePointer);
// Display the
student record
printf("Name: %sRoll Number: %d\n", student.name,
student.rollNumber);
}
// Close the file
fclose(filePointer);
return 0;
}
In this example:
The file is opened in binary mode with "rb+" to
allow both reading and writing.
The file pointer is moved to the end of the file using
fseek() with SEEK_END as the origin.
The total number of records in the file is determined using
ftell() to get the current position of the file pointer.
A new student record is written at the end of the file using
fwrite().
The file pointer is moved back to the beginning of the file
for reading.
All student records are read and displayed.
Note: This is just a simple example, and in a real-world
scenario, error handling and additional considerations for data input and
output would be necessary.
Random access input-output in C language
Random access input-output in C involves reading and writing
data at arbitrary positions within a file. To achieve random access, the
fseek() function is used to set the file position indicator, and then the data
can be read or written using functions like fread() and fwrite(). The ftell()
function is often used to determine the current position of the file pointer.
Here's an example demonstrating random access input-output in
C:
#include <stdio.h>
struct Student {
char name[50];
int rollNumber;
};
int main() {
FILE *filePointer;
// Open a binary
file for reading and writing
filePointer =
fopen("students.dat", "rb+");
// Check if the
file is successfully opened
if (filePointer ==
NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program with an error code
}
// Move the file
pointer to a specific record position (e.g., the third record)
long recordNumber =
2; // 0-based index
fseek(filePointer,
recordNumber * sizeof(struct Student), SEEK_SET);
// Example:
Reading a specific student record
struct Student
student;
fread(&student, sizeof(struct Student), 1, filePointer);
// Display the
read student record
printf("Read
Student Record:\n");
printf("Name:
%s", student.name);
printf("Roll
Number: %d\n", student.rollNumber);
// Move the file
pointer to another position (e.g., the end of the file)
fseek(filePointer,
0, SEEK_END);
// Example:
Writing a new student record at the end of the file
struct Student
newStudent;
printf("\nEnter new student name: ");
fgets(newStudent.name, sizeof(newStudent.name), stdin);
printf("Enter
new roll number: ");
scanf("%d", &newStudent.rollNumber);
// Write the new
student record at the end of the file
fwrite(&newStudent, sizeof(struct Student), 1, filePointer);
// Move the file
pointer back to the beginning of the file
fseek(filePointer,
0, SEEK_SET);
// Display all
student records
printf("\nAll
Student Records:\n");
long totalRecords
= ftell(filePointer) / sizeof(struct Student);
for (long i = 0; i
< totalRecords; i++) {
struct Student
student;
// Read a
student record from the file
fread(&student, sizeof(struct Student), 1, filePointer);
// Display the
student record
printf("Name: %s", student.name);
printf("Roll Number: %d\n", student.rollNumber);
}
// Close the file
fclose(filePointer);
return 0;
}
In this example:
The file is opened in binary mode with "rb+" to
allow both reading and writing.
The fseek() function is used to move the file pointer to
specific positions within the file.
fread() and fwrite() are used to read and write data at the
specified positions.
ftell() is used to determine the current position of the
file pointer.
The program reads a specific student record, writes a new
student record at the end of the file, and then displays all student records.
Remember to handle errors appropriately, especially when
dealing with file operations. Also, keep in mind that random access operations
might be less efficient compared to sequential access, especially for large
files.
Comments
Post a Comment