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

Ch5 File Handling

This document covers file handling in C, including the basics of computer files, file modes (read, write, append), and access methods (sequential and random). It explains key functions such as fopen, fputs, fgetc, and fseek, providing examples for reading from and writing to files. The document also highlights error handling and the importance of closing files after operations.

Uploaded by

jojac32799
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Ch5 File Handling

This document covers file handling in C, including the basics of computer files, file modes (read, write, append), and access methods (sequential and random). It explains key functions such as fopen, fputs, fgetc, and fseek, providing examples for reading from and writing to files. The document also highlights error handling and the importance of closing files after operations.

Uploaded by

jojac32799
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Computational Thinking for

Structured Design-2
Chapter- 5
FILE HANDLING
CONTENT
● Basics of Computer Files
● Working on Different File Operations (Read, Write and Append)
● Understanding of Access of Files: Sequential Access and
Random Access
What is Basics of Computer Files in C ?
● Definition: A FILE * variable is used to represent a connection
to a file. Think of it as a handle to the file.
● Syntax:
● FILE * variableName;
● variableName shall be used to store a file in itself
Basic FILE MODES
r (Read mode): w (Write mode): a (Append mode):
• Use this mode when you • Use this mode when you • Use this mode when you
want to read information want to write new want to add new
from a file. information into a file. information to the end of
• • a file.
The file must already If the file already exists,
• It won’t delete what’s
exist; otherwise, it will it will erase everything already in the file; it just
show an error. inside it and start fresh. adds more content to it.
• Example: Like opening a • If the file doesn’t exist, it • If the file doesn’t exist, it
book just to read it, will create a new one. will create a new one.
without making any • Example: Like using a • Example: Like adding
changes. blank notebook to write notes to the end of a
something. notebook you’re already
using.
What is Access of Files?
• It refers to how data is read from or written to files stored on a disk or another storage medium.
• The mode of access determines how the file data is accessed, whether sequentially or randomly.
Types Of Access of Files

Types Of Access of Files Types Of Access of Files


• Data is read or written sequentially • Data is accessed directly at any
from the beginning of the file to the location in the file without reading
end. through the preceding data.
• Suitable for applications where data is • Suitable for applications where data
processed in order (e.g., reading logs needs to be accessed or modified at
or records in order). arbitrary positions (e.g., databases or
indexed files).
• It uses functions like fgetc, fgets,
fscanf, fputc, fputs, and fprintf. • It uses functions like fseek, ftell, and
rewind.
Sequential Access
How to Use Sequential Access?
Why Use Sequential Access?
• Simple to implement. #include <stdio.h>
int main() {
• Efficient for processing files where the order of data is important. FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
char ch;
printf("Reading file sequentially:\n");
while ((ch = fgetc(file)) != EOF) { // Read character by
character
putchar(ch); // Print each character
}
fclose(file);
return 0;
}
What is fopen()?
• fopen() is a function used to open a file in C or C++.
• It allows you to work with the file (read, write, or append) depending on the
specified mode.
What happens if the file doesn’t exist?
• If the file doesn’t exist, fopen() will return NULL, meaning the file couldn’t be
opened or found. • FILE *fptr: This is a pointer to a file that
will be used for file operations.
Syntax of fopen() : FILE *fptr; • "filename.txt": The name of the file you
want to open. (It can also include the file's
path.)
fptr = fopen("filename.txt", "mode"); • "mode": The mode in which you want to
open the file (e.g., "r", "w", "a").
Example
#include <stdio.h>

int main() { Explanation


FILE *fptr; // Declare a file pointer
fptr = fopen("example.txt", "r"); // Open the file in read mode • If the file "example.txt" exists, the
program will open it and print "File
if (fptr == NULL) { opened successfully."
printf("Error: File not found!\n"); • If the file doesn’t exist, it will print
} else { "Error: File not found!"
printf("File opened successfully.\n");
fclose(fptr); // Close the file
}
return 0;
}
What is fputs()?
• fputs() is used to write a string to a file.
• It writes the string exactly as it is (no newline added automatically).
It returns:
• A non-negative value if writing was successful.
• EOF (End of File) if there’s an error.

Syntax:
int fputs(const char *str, FILE *stream);
• str: The string you want to write into the file.
• stream: The file pointer (opened using fopen())
What is fputs()?
Key Points:
• Doesn't Add a Newline Automatically:
• If you want a new line, you have to add \n at the end of the string manually: fputs("Hello,
world!\n", fptr);
• File Must Be Opened in Write (w) or Append (a) Mode:
• Opening in write mode (w) overwrites the file.
• Opening in append mode (a) adds the string to the end of the file.
• Error Handling:
• Always check if the file was opened successfully (fptr != NULL).
Example
#include <stdio.h> // Write a string to the file
int main() { fputs("Hello, world!", fptr);
FILE *fptr;
// Open file in write mode // Close the file
fptr = fopen("example.txt", "w"); fclose(fptr);
// Check if file was opened successfully
if (fptr == NULL) { printf("String written to the file successfully.\
printf("Error: File could not be opened!\n"); n");
return 1;
} return 0;
}
WRITING INTO A FILE (alternate way using fgets())
#include <stdio.h>
#include <stdlib.h> fgets(): Reads at most n-1 characters from
int main() { the input stream stream into the string str,
FILE *fptr;
char line[100];
stopping at a newline or EOF. It null-
fptr = fopen("myfile.txt", "r"); terminates the string. Returns str on
if (fptr == NULL) { success, or NULL on error or EOF.
printf("Error opening file!\n");
exit(1);
}
printf("Contents of the file (line by line):\n");
while (fgets(line, sizeof(line), fptr) != NULL) {
printf("%s", line);
}
fclose(fptr);
return 0;
}
READING FROM A FILE
#include <stdio.h>
#include <stdlib.h> fgetc(): Reads the next character from the input
int main() {
FILE *fptr;
stream stream and returns its integer value.
char ch; Returns EOF (usually -1) on end-of-file or error.
fptr = fopen("myfile.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("Contents of the file:\n");
while ((ch = fgetc(fptr)) != EOF) {
printf("%c", ch); // Print each character to the console
}
fclose(fptr);
return 0;
}
CLOSING A FILE
#include <stdio.h>
#include <stdlib.h> fclose(): Closes the file associated with the
int main() { stream stream, flushing any buffered output.
FILE *fptr;
fptr = fopen("myfile.txt", "w");
Returns 0 on success, or EOF on error.
if (fptr == NULL) {
perror("Error opening file");
exit(1);
}
fprintf(fptr, "This is some text.\n");
if (fclose(fptr) == EOF) {
perror("Error closing file");
exit(1);
}
printf("File closed successfully.\n");
fptr = NULL;
return 0;
}
Random Access
Why Use Random Access?
• Efficient when only specific parts of a file need to be read or modified.
• Reduces overhead as you can jump directly to the desired part of the file.

How to Use Random Access?

• Use fseek to move the file pointer to a specific position.

• Use ftell to determine the current position of the file pointer.

• Use rewind to reset the file pointer to the beginning of the file.
Random Access (Conti...)
Syntax:
1. fseek(FILE *stream, long int offset, int whence);
• stream: Pointer to the file.
• offset: Number of bytes to move the pointer.
• whence: Reference point (SEEK_SET, SEEK_CUR, SEEK_END).

2. ftell(FILE *stream);
• Returns the current position of the file pointer.

3. rewind(FILE *stream);
• Sets the file pointer to the beginning of the file.
Random Access Example
#include <stdio.h> // Read character at the 5th byte
int main() { char ch = fgetc(file);
FILE *file = fopen("example.txt", "r+"); printf("Character at 5th position: %c\n", ch);
if (file == NULL) { // Modify the 5th byte
printf("Error opening file.\n"); fseek(file, 4, SEEK_SET); // Move back to 5th position
return 1; fputc('X', file);
} printf("Modified 5th position with 'X'.\n");
// Move file pointer to the 5th byte fclose(file);
fseek(file, 4, SEEK_SET); return 0;
} r+ Mode: Opens the file for both reading and writing. The file must already
exist.
Explanation Of Example
Open the File:
• Opens example.txt in read-and-write mode (r+). If the file cannot be opened, an error is displayed.

Move File Pointer:


• Uses fseek to move the file pointer to the 5th byte (index 4 from the start).

Read a Character:
• Reads the character at the 5th byte using fgetc and prints it.

Modify the 5th Byte:


• Moves the file pointer back to the 5th byte and writes 'X' using fputc, replacing the original character.

Close the File:


• Ensures changes are saved and releases file resources.
Output Of Example
Character at 5th position: o
• If the file initially contains: HelloWorld Modified 5th position with 'X'.

• The file becomes: HellXWorld

Key Functions:

• fseek: Move the file pointer to a specific position.

• fgetc: Read a character at the current pointer position.

• fputc: Write/modify a character at the current pointer position.


THANK YOU

You might also like