Ch5 File Handling
Ch5 File Handling
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
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.
• 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.
Read a Character:
• Reads the character at the 5th byte using fgetc and prints it.
Key Functions: