Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views2 pages

File 6

A file is a collection of data stored on a storage device, used for persistent data storage and input/output operations in programming. Common file operations include opening, reading, writing, and closing files, with various modes for each operation. The document also provides a C program example demonstrating how to write and read text from a file.

Uploaded by

royrian149
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

File 6

A file is a collection of data stored on a storage device, used for persistent data storage and input/output operations in programming. Common file operations include opening, reading, writing, and closing files, with various modes for each operation. The document also provides a C program example demonstrating how to write and read text from a file.

Uploaded by

royrian149
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

What is a File?

A file is a collection of data stored on a storage device, such as a hard disk or SSD. Files are
used to store data persistently, even after a program ends. In programming, files are typically
used for input/output operations.

File Operations

Files can be handled using various operations. The most common ones are:

1. Opening a File: Open a file in a specific mode (e.g., read, write).

r - Open for reading.

w - Open for writing (overwrites existing content).

a - Open for appending (adds to the end of the file).

r+, w+, a+ - Open for both reading and writing.

2. Reading from a File: Retrieve data from the file using functions like fgetc(), fgets(), or fscanf().

3. Writing to a File: Add content to the file using functions like fputc(), fputs(), or fprintf().

4. Closing a File: Close the file using fclose() to release resources.

---

C Program: Writing and Reading Text into a File

#include <stdio.h>

int main() {
FILE *filePointer;
char text[100];
filePointer = fopen("example.txt", "w");
if (filePointer == NULL)
{
printf("Error opening file for writing.\n");
return 1;
}

printf("Enter text to write into the file: ");


fgets(text, sizeof(text), stdin);
fprintf(filePointer, "%s", text);
fclose(filePointer);
printf("Text written to file successfully.\n");
filePointer = fopen("example.txt", "r");
if (filePointer == NULL)
{
printf("Error opening file for reading.\n");
return 1;
}

printf("Content of the file:\n");


while (fgets(text, sizeof(text), filePointer) != NULL)
{
printf("%s", text);
}

fclose(filePointer);
return 0;
}

---

You might also like