Unit 6: File Handling - Subjective Questions
CAP1008 — C Programming • Practice Questions with Detailed Answers
20 questions
Define a file in the context of C programming. Explain why file handling is important in real-world applications.
A file is a collection of related data or information stored on a secondary storage device (such as a hard disk) under a specific name. In C, a file is treated as a sequence of bytes.
Importance of file handling:
- Persistent storage: Data stored in variables is lost once the program terminates. Files store data permanently.
- Large data handling: Files can store large volumes of data that cannot be kept in memory at once.
- Data reusability: Data can be retrieved and reused across multiple program executions.
- Data sharing: Files allow data to be shared between different programs and users.
- Reduced manual effort: Instead of re-entering data every time, it can be read directly from a file.
C provides a standard library <stdio.h> with functions to create, open, read, write, and close files.
Describe the different categories of files used in C programming.
Files in C are broadly categorized based on how data is stored and accessed:
1. Based on content/format:
- Text Files: Store data as sequences of ASCII characters. Human-readable and can be opened in any text editor. Each line ends with a newline character.
- Binary Files: Store data in binary form (the same format used in memory). Not human-readable but more efficient in space and speed.
2. Based on access method:
- Sequential Access Files: Data is read/written in a sequential manner from beginning to end.
- Random Access Files: Data can be read/written at any position using functions like
fseek()andftell().
3. Based on standard streams (predefined files):
- stdin: Standard input (keyboard)
- stdout: Standard output (screen)
- stderr: Standard error output (screen)
These categories help programmers choose the appropriate file type and access method for their needs.
Distinguish between text files and binary files in C with suitable examples.
| Feature | Text File | Binary File |
|---|---|---|
| Storage format | Data stored as ASCII characters | Data stored in binary (raw bytes) |
| Readability | Human-readable | Not human-readable |
| Size | Generally larger | More compact |
| Newline handling | May translate \n to \r\n (on Windows) |
No translation |
| Mode specifier | "r", "w", "a" |
"rb", "wb", "ab" |
| Functions used | fprintf(), fscanf(), fgets(), fputs() |
fwrite(), fread() |
| Portability | More portable across systems | Less portable (depends on system) |
Example - Text file:
c
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Age: %d", 25);
fclose(fp);
Example - Binary file:
c
int age = 25;
FILE *fp = fopen("data.bin", "wb");
fwrite(&age, sizeof(int), 1, fp);
fclose(fp);
Text files are preferred for readability, while binary files are preferred for efficiency and exact data representation.
Explain the process of opening a file in C using the fopen() function. Describe its syntax and return value.
The fopen() function is used to open a file and associate it with a file pointer (stream).
Syntax:
c
FILE fopen(const char filename, const char *mode);
- filename: Name (and path) of the file to open.
- mode: A string specifying the purpose of opening (read, write, append, etc.).
Return value:
- On success,
fopen()returns a pointer to aFILEstructure. - On failure (e.g., file not found in read mode), it returns
NULL.
Example:
c
FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Error: File could not be opened.\n");
exit(1);
}
Key points:
- Always check whether the returned pointer is
NULLbefore performing operations. - The
FILEstructure holds information about the file such as the current position, buffer, and status. - The file pointer acts as a link between the program and the physical file.
List and explain the various file opening modes available in C.
File modes specify the operations allowed on a file. The main modes are:
Text mode:
"r"– Open for reading. File must exist, else returnsNULL."w"– Open for writing. Creates a new file or overwrites an existing one."a"– Open for appending. Data added at the end; file created if it doesn't exist."r+"– Open for both reading and writing. File must exist."w+"– Open for reading and writing. Overwrites existing or creates new."a+"– Open for reading and appending. Creates file if it doesn't exist.
Binary mode: Add b to the above modes:
"rb","wb","ab","rb+","wb+","ab+"– Same as above but for binary files.
Example:
c
FILE *fp = fopen("record.dat", "wb");
Key point: Choosing the correct mode is critical because using "w" on an existing file erases all its contents.
Explain the importance of closing a file in C. Describe the fclose() function with syntax and example.
Closing a file after use is an essential step in file handling.
Importance of closing a file:
- Flushes buffers: Ensures all data in the buffer is written to the physical file.
- Frees resources: Releases the memory and file descriptor associated with the file.
- Prevents data loss/corruption: Unclosed files may lose unsaved data.
- Limits on open files: Operating systems limit the number of simultaneously open files; closing frees these slots.
Syntax:
c
int fclose(FILE *fp);
- Returns 0 on success.
- Returns EOF on failure.
Example:
c
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hello World");
if (fclose(fp) == 0)
printf("File closed successfully.\n");
Note: To close all open streams at once, fcloseall() can be used (though it is non-standard). Good practice is to close each file explicitly once operations are complete.
Describe the character input/output functions getc()/fgetc() and putc()/fputc() with examples.
These functions read and write a single character at a time to/from a file.
Reading a character - fgetc() / getc():
c
int fgetc(FILE *fp);
- Reads a single character from the file.
- Returns the character read (as an
int) orEOFat end of file.
Writing a character - fputc() / putc():
c
int fputc(int ch, FILE *fp);
- Writes a single character to the file.
- Returns the character written or
EOFon error.
Example - copying a file character by character:
c
FILE src = fopen("in.txt", "r");
FILE dst = fopen("out.txt", "w");
int ch;
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dst);
}
fclose(src);
fclose(dst);
Note: getc() and putc() are similar but may be implemented as macros, while fgetc() and fputc() are always functions.
Explain the string handling functions fgets() and fputs() used in file operations with syntax and examples.
These functions read and write strings (lines) to/from files.
Reading a string - fgets():
c
char fgets(char str, int n, FILE *fp);
- Reads up to
n-1characters or until a newline/EOF. - Stores the string in
strand appends a null terminator\0. - Returns
stron success,NULLon error/EOF.
Writing a string - fputs():
c
int fputs(const char str, FILE fp);
- Writes the string to the file (without adding a newline).
- Returns a non-negative value on success,
EOFon error.
Example:
c
char line[100];
FILE *fp = fopen("data.txt", "r");
while (fgets(line, 100, fp) != NULL) {
fputs(line, stdout); // print to screen
}
fclose(fp);
Key difference from gets()/puts(): fgets() is safer than gets() because it limits the number of characters read, preventing buffer overflow.
Explain the formatted I/O functions fprintf() and fscanf() with syntax and a suitable example program.
fprintf() and fscanf() perform formatted input/output on files, similar to printf() and scanf() but directed to a file stream.
Writing formatted data - fprintf():
c
int fprintf(FILE fp, const char format, ...);
Reading formatted data - fscanf():
c
int fscanf(FILE fp, const char format, ...);
Example - writing and reading student data:
c
// Writing
FILE *fp = fopen("student.txt", "w");
fprintf(fp, "%s %d %.2f", "Ram", 21, 85.5);
fclose(fp);
// Reading
char name[20];
int age;
float marks;
fp = fopen("student.txt", "r");
fscanf(fp, "%s %d %f", name, &age, &marks);
printf("Name: %s, Age: %d, Marks: %.2f", name, age, marks);
fclose(fp);
Key points:
- These functions are ideal for text files with structured data.
fscanf()returns the number of items successfully read, orEOF.
Explain the block I/O functions fread() and fwrite() used for reading and writing binary files. Illustrate with an example.
fread() and fwrite() are used to read and write blocks of data (records/structures) to binary files.
Writing a block - fwrite():
c
size_t fwrite(const void ptr, size_t size, size_t count, FILE fp);
Reading a block - fread():
c
size_t fread(void ptr, size_t size, size_t count, FILE fp);
- ptr: Pointer to the data block.
- size: Size of each element in bytes.
- count: Number of elements.
- Return value: Number of elements successfully read/written.
Example - storing a structure:
c
struct Student {
char name[20];
int roll;
};
struct Student s = {"Sita", 5};
// Write
FILE *fp = fopen("stu.dat", "wb");
fwrite(&s, sizeof(struct Student), 1, fp);
fclose(fp);
// Read
struct Student r;
fp = fopen("stu.dat", "rb");
fread(&r, sizeof(struct Student), 1, fp);
printf("%s %d", r.name, r.roll);
fclose(fp);
Advantage: These functions handle entire records efficiently, making them ideal for database-like applications.
Compare sequential file access and random file access in C. Explain the role of fseek(), ftell(), and rewind().
Sequential Access: Data is read or written in order from the beginning to the end of the file. To access a particular record, all preceding records must be traversed.
Random Access: Data can be accessed directly at any position in the file without reading previous data, using file positioning functions.
| Aspect | Sequential Access | Random Access |
|---|---|---|
| Order | Beginning to end | Any position |
| Speed | Slow for large files | Fast direct access |
| Functions | fscanf, fprintf |
fseek, ftell, rewind |
File positioning functions:
fseek(FILE *fp, long offset, int origin)– Moves the file pointer to a specific position.origincan beSEEK_SET(start),SEEK_CUR(current), orSEEK_END(end).ftell(FILE *fp)– Returns the current position of the file pointer (in bytes from start).rewind(FILE *fp)– Moves the file pointer back to the beginning of the file.
Example:
c
fseek(fp, 0, SEEK_END); // move to end
long size = ftell(fp); // get file size
rewind(fp); // back to start
Write a C program to read the contents of a text file and display it on the screen. Explain the logic used.
Program:
c
include <stdio.h>
include <stdlib.h>
int main() {
FILE *fp;
char ch;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
printf("Error: Unable to open file.\n");
exit(1);
}
// Read and display each character until EOF
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
Logic explanation:
- Open the file in read mode
"r"usingfopen(). - Check for NULL to ensure the file opened successfully.
- Read character by character using
fgetc()inside a loop until the end-of-file markerEOFis reached. - Display each character on screen using
putchar(). - Close the file with
fclose()to release resources.
This approach efficiently displays the entire content of a text file.
Explain the concept of the End-of-File (EOF) marker and the feof() function in C file handling.
EOF (End-of-File):
EOFis a special constant (usually defined as-1) in<stdio.h>that indicates the end of a file has been reached.- File-reading functions like
fgetc(),fscanf(), andgetc()returnEOFwhen there is no more data to read.
The feof() function:
c
int feof(FILE *fp);
- Returns a non-zero value if the end of the file has been reached, otherwise returns 0.
Example:
c
FILE *fp = fopen("data.txt", "r");
char ch;
while (!feof(fp)) {
ch = fgetc(fp);
if (ch != EOF)
putchar(ch);
}
fclose(fp);
Important note: Using feof() in the loop condition can sometimes cause the last line to be read twice, because feof() only becomes true after a read attempt fails. Therefore, checking the return value of the read function directly (e.g., while((ch = fgetc(fp)) != EOF)) is generally the preferred and safer approach.
Write a C program to copy the contents of one file into another file. Explain each step.
Program:
c
include <stdio.h>
include <stdlib.h>
int main() {
FILE src, dest;
char ch;
src = fopen("source.txt", "r");
if (src == NULL) {
printf("Source file cannot be opened.\n");
exit(1);
}
dest = fopen("destination.txt", "w");
if (dest == NULL) {
printf("Destination file cannot be created.\n");
fclose(src);
exit(1);
}
// Copy content character by character
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dest);
}
printf("File copied successfully.\n");
fclose(src);
fclose(dest);
return 0;
}
Step-by-step explanation:
- Open source file in read mode and destination file in write mode.
- Validate both file pointers for
NULL. - Read each character from the source using
fgetc(). - Write each character to the destination using
fputc()untilEOF. - Close both files to save data and free resources.
What is a file pointer in C? Explain the role of the FILE structure in file handling.
File Pointer:
A file pointer is a pointer variable of type FILE * that points to a FILE structure. It serves as a link between the program and the file stored on disk. All file operations are performed through this pointer.
Declaration:
c
FILE *fp;
The FILE structure:
FILE is a predefined structure declared in <stdio.h>. It stores important information about an open file, including:
- Current position of the file pointer (read/write location)
- Buffer used for temporary storage of data
- File mode (read, write, append)
- End-of-file and error status flags
- File descriptor used by the operating system
Role in file handling:
- When
fopen()is called, it returns a pointer to aFILEstructure. - The program uses this pointer to identify which file to operate on.
- Functions like
fread(),fwrite(),fprintf(), etc., use the file pointer to access the correct file and track the current position automatically.
Example:
c
FILE *fp = fopen("data.txt", "r");
// fp now points to the FILE structure of data.txt
Explain how to perform reading and writing of structures into a binary file in C with a complete example program.
Structures are commonly stored in binary files using fwrite() and fread() since they preserve the exact memory representation of data.
Complete Program:
c
include <stdio.h>
include <stdlib.h>
struct Employee {
int id;
char name[30];
float salary;
};
int main() {
struct Employee e1 = {101, "Hari", 45000.50};
struct Employee e2;
FILE *fp;
// Writing structure to binary file
fp = fopen("emp.dat", "wb");
if (fp == NULL) { printf("Error!\n"); exit(1); }
fwrite(&e1, sizeof(struct Employee), 1, fp);
fclose(fp);
// Reading structure from binary file
fp = fopen("emp.dat", "rb");
fread(&e2, sizeof(struct Employee), 1, fp);
fclose(fp);
printf("ID: %d\n", e2.id);
printf("Name: %s\n", e2.name);
printf("Salary: %.2f\n", e2.salary);
return 0;
}
Explanation:
- The file is opened in binary write mode
"wb". fwrite()writes the entire structure at once usingsizeof(struct Employee).- The file is reopened in binary read mode
"rb". fread()reads the structure back into another variable.- This method is efficient and preserves data types exactly.
Describe the complete file handling process in C, from opening to closing a file, covering all essential steps. Support your answer with a general program structure.
File handling in C follows a systematic sequence of steps:
1. Declare a file pointer:
c
FILE *fp;
2. Open the file using fopen() with an appropriate mode:
c
fp = fopen("data.txt", "w");
3. Check whether the file opened successfully:
c
if (fp == NULL) {
printf("File could not be opened.\n");
exit(1);
}
4. Perform file operations (read/write) using suitable functions:
- Writing:
fprintf(),fputc(),fputs(),fwrite() - Reading:
fscanf(),fgetc(),fgets(),fread()
5. Close the file using fclose() to flush buffers and free resources:
c
fclose(fp);
General program structure:
c
include <stdio.h>
include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
exit(1);
}
fprintf(fp, "Hello File Handling");
fclose(fp);
return 0;
}
Summary: The lifecycle is Declare → Open → Validate → Process → Close. Following these steps ensures reliable and error-free file operations.
Distinguish between the file functions fprintf()/fscanf() and fwrite()/fread(). When should each pair be used?
| Feature | fprintf() / fscanf() |
fwrite() / fread() |
|---|---|---|
| Type of I/O | Formatted (text) I/O | Block/binary I/O |
| Data format | Converts data to/from readable text | Stores raw binary (memory image) |
| File type | Best for text files | Best for binary files |
| Readability | Output is human-readable | Output not human-readable |
| Speed | Slower (conversion overhead) | Faster (no conversion) |
| Size | Larger storage | Compact storage |
| Ideal use | Simple structured text data | Records, structures, arrays |
When to use fprintf()/fscanf():
- When data needs to be readable/editable in a text editor.
- When storing simple values like names, numbers in text form.
When to use fwrite()/fread():
- When storing large amounts of structured data (like structures or arrays).
- When speed and space efficiency matter.
- When exact binary representation must be preserved (e.g., floating-point precision).
Conclusion: Choose text-based functions for readability and portability; choose binary block functions for efficiency and precise data storage.
Explain error handling in file operations in C. Discuss the use of ferror(), perror(), and checking return values.
Error handling ensures that file operations fail gracefully and provide meaningful feedback.
1. Checking fopen() return value:
Always verify if the file opened successfully:
c
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("File could not be opened.\n");
exit(1);
}
2. The ferror() function:
c
int ferror(FILE *fp);
- Returns a non-zero value if an error occurred during a file operation, otherwise 0.
c
if (ferror(fp))
printf("An error occurred while accessing the file.\n");
3. The perror() function:
c
void perror(const char *str);
- Prints a descriptive error message based on the global variable
errno, along with the user-supplied string.
c
if (fp == NULL)
perror("Error"); // e.g., "Error: No such file or directory"
4. Checking return values of read/write functions:
fread()/fwrite()return the number of elements processed.fscanf()returns the number of items read.- Comparing these against expected values detects partial or failed operations.
5. clearerr() can reset error and EOF indicators.
Conclusion: Proper error handling prevents crashes and data corruption, making programs robust and reliable.
Write a C program to count the number of characters, words, and lines in a text file. Explain the logic.
Program:
c
include <stdio.h>
include <stdlib.h>
int main() {
FILE *fp;
char ch;
int characters = 0, words = 0, lines = 0;
fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Cannot open file.\n");
exit(1);
}
while ((ch = fgetc(fp)) != EOF) {
characters++;
if (ch == ' ' || ch == '\t' || ch == '\n')
words++;
if (ch == '\n')
lines++;
}
// Adjust counts
if (characters > 0) {
words++; // account for the last word
lines++; // account for the last line
}
printf("Characters: %d\n", characters);
printf("Words: %d\n", words);
printf("Lines: %d\n", lines);
fclose(fp);
return 0;
}
Logic explanation:
- Open the file in read mode and validate.
- Read each character until
EOF, incrementing the character count. - Count words by detecting spaces, tabs, or newlines as separators.
- Count lines by detecting newline characters
\n. - Adjust final counts to include the last word and line if the file is non-empty.
- Close the file at the end.
This is a common text-processing application demonstrating character-level file reading.
Define a file in the context of C programming. Explain why file handling is important in real-world applications.
A file is a collection of related data or information stored on a secondary storage device (such as a hard disk) under a specific name. In C, a file is treated as a sequence of bytes.
Importance of file handling:
- Persistent storage: Data stored in variables is lost once the program terminates. Files store data permanently.
- Large data handling: Files can store large volumes of data that cannot be kept in memory at once.
- Data reusability: Data can be retrieved and reused across multiple program executions.
- Data sharing: Files allow data to be shared between different programs and users.
- Reduced manual effort: Instead of re-entering data every time, it can be read directly from a file.
C provides a standard library <stdio.h> with functions to create, open, read, write, and close files.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →