- Asked 2/16
- 2070 Chaitra · 4 marks
- 2068 Shrawan · 1+3 marks
Opening and closing a data file
Short answer
Opening a file with fopen connects a disk file to a FILE pointer, specifying mode (r, w, a). Always check for NULL. Closing with fclose flushes buffers, releases resources, and prevents data loss.
What do you mean by opening a data file? How is this accomplished? Define opening and closing a file along with suitable examples.
Opening a file
Opening a file means connecting a file on the disk to a program through a file pointer, so that the program can read from or write to it. The function fopen() does this:
FILE *fp = fopen("filename", "mode");
It returns the file pointer, or NULL if the file cannot be opened (for example, a file for reading does not exist), so the result must always be checked. Common modes: "r" read, "w" write (creates/erases), "a" append.
Closing a file
fclose(fp); disconnects the file: it writes the remaining buffered data to the disk, releases the file pointer and the resources of the system, and prevents data loss. The number of files that can be open at one time is limited, so files should be closed when work is finished.
#include <stdio.h>
int main(void)
{
FILE *fp; /* file pointer */
fp = fopen("data.txt", "w"); /* open for writing */
if (fp == NULL) { /* check that opening succeeded */
printf("Unable to open the file\n");
return 1;
}
fprintf(fp, "Hello file\n");
fclose(fp); /* close: flush buffer, free the file */
printf("File written and closed\n");
return 0;
}
Output: File written and closed
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Data file and file modes · Computer Programming, chapter 10
- Macro expansion and file inclusion · Computer Programming, chapter 3
- Copy contents of one file to another · Computer Programming, chapter 10 · asked 2×
- Store 48 students in file with append · Computer Programming, chapter 10
- Employee text file; sort into binary file · Computer Programming, chapter 10
- INVENTORY file of items · Computer Programming, chapter 10
- Laplace: current with S1 closing and S2 opening at 4 ms · Electrical Circuit Theory, chapter 4
- Selecting support type for underground opening · Engineering Geology II, chapter 6
- Stream and file stream classes · Object Oriented Programming, chapter 8
- Google File System architecture · Big Data Technologies, chapter 2 · asked 2×