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

Files

The document provides an overview of file handling in C, detailing the use of the FILE data type and file pointers for operations such as reading, writing, and updating files. It distinguishes between text and binary files, outlines various file operations including opening and closing files, and demonstrates how to copy files and manipulate file pointers using functions like fseek(). Additionally, it includes examples of working with binary data and constants used in file positioning.
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)
2 views

Files

The document provides an overview of file handling in C, detailing the use of the FILE data type and file pointers for operations such as reading, writing, and updating files. It distinguishes between text and binary files, outlines various file operations including opening and closing files, and demonstrates how to copy files and manipulate file pointers using functions like fseek(). Additionally, it includes examples of working with binary data and constants used in file positioning.
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/ 11

Files

Introduction to Files in C

In C, files are used to store and retrieve data permanently. Unlike variables, the
data stored in files is not lost when the program ends.

To work with files, C uses a special data type called FILE, defined in the
<stdio.h> header.

File Pointer

To perform any file operation, we use a file pointer, which is a pointer to a


structure of type FILE.

FILE *fp;

a file pointer is a special pointer of type FILE* that is used to access and
manipulate files.This pointer is used with functions like fopen(), fclose(),
fread(), fwrite(), etc.It points to a structure that holds information about the
file (such as current position, mode, etc.).

File Types

1. Text Files

• Store data in human-readable characters.


• Each line ends with a newline character (\n).
• Example: .txt, .csv
2. Binary Files

• Store data in binary (0s and 1s).


• Not human-readable.
• More efficient and compact.
• Example: .dat, .bin

Text Files vs Binary Files

Feature Text File Binary File

Format Human-readable Machine-readable (binary)

Size Larger Smaller

Speed Slower Faster

Portability More portable Less portable

Use Logs, config files, reports Images, executables, databases


File Operations in C

Opening Files — fopen()

To open a file:

FILE *fp = fopen("filename.txt", "mode");

Modes:

Mode Meaning

"r" Read (file must exist)

"w" Write (create or truncate)

"a" Append (add to end of file)

"r+" Read & Write

"w+" Read & Write (create or truncate)

"a+" Read & Append

"rb", "wb", "ab", etc. For binary files

❌ Closing Files — fclose()

Always close files after operations to free memory:

fclose(fp);
Reading from Files

fgetc()

Reads a single character:

char ch = fgetc(fp);

fgets()

Reads a string (line):

char str[100];
fgets(str, 100, fp);

fread()

Reads binary data:

fread(&data, sizeof(data_type), count, fp);

Writing to Files

fputc()

Writes a single character:

fputc('A', fp);

fputs()

Writes a string:
fputs("Hello, world!", fp);

fwrite()

Writes binary data:

fwrite(&data, sizeof(data_type), count, fp);

Updating Files (Read and Write)

To read and write in the same file:

• Use modes like "r+", "w+", "a+"


• Use fseek() to move the file pointer to the desired location if needed

Example:

FILE *fp = fopen("data.txt", "r+");


fputs("Updated!", fp);
fclose(fp);

Binary and Sequential Files

Sequential File Access

• Data is accessed one after another.


• Works like reading a book from start to finish.
• Example: text file with lines of data.
Random File Access

• Access any part of the file directly using file position pointer.
• Use fseek() and ftell() functions.
• Needed for binary files or when updating specific records.

How to Copy One File to Another in C


Example Program:
#include <stdio.h>

int main() {
FILE *sourceFile, *destFile;
char ch;

// Open source file in read mode


sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Cannot open source file.\n");
return 1;
}

// Open destination file in write mode


destFile = fopen("destination.txt", "w");
if (destFile == NULL) {
printf("Cannot open destination file.\n");
fclose(sourceFile);
return 1;
}

// Copy character by character


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destFile);
}

printf("File copied successfully.\n");


fclose(sourceFile);
fclose(destFile);
return 0;}

• Explanation:

• fopen() opens both files: one for reading, one for writing.

• fgetc() reads one character at a time from source.

• fputc() writes that character to the destination.

• The loop continues until end of file (EOF) is reached.

• fclose() closes both files.

Constants Used in fseek()


The fseek() function is used to move the file pointer to a specific location in the file.

• fseek(file_pointer, offset, position);

file_pointer: the file being accessed.


• offset: how many bytes to move.
• position: from where to move (uses one of the constants below).

fseek(fp, 0, SEEK_SET); // Move to the beginning

fseek(fp, 10, SEEK_CUR); // Move 10 bytes forward from current position

fseek(fp, -5, SEEK_END); // Move 5 bytes backward from end of file


#include <stdio.h>

int main() {

FILE *fp;

char ch;

// Open file in read mode

fp = fopen("sample.txt", "r");

if (fp == NULL) {

printf("Error: Cannot open file.\n");

return 1;

// SEEK_SET: Move to the beginning (0th byte)

fseek(fp, 0, SEEK_SET);

printf("Reading from start:\n");

ch = fgetc(fp);

printf("Character: %c\n\n", ch); // Should print 'H'

// SEEK_CUR: Move 10 bytes ahead from current position

fseek(fp, 10, SEEK_CUR);

printf("Reading 10 bytes after current:\n");

ch = fgetc(fp);

printf("Character: %c\n\n", ch); // Depends on file content

// SEEK_END: Move 5 bytes before end of file


fseek(fp, -5, SEEK_END);

printf("Reading 5 bytes before end:\n");

ch = fgetc(fp);

printf("Character: %c\n\n", ch); // Depends on file content

fclose(fp);

Output Explanation (if the content is as above):

1. From SEEK_SET:
Output: H (1st character)
2. From SEEK_CUR (10 chars ahead from 2nd position):
Output: Likely h or a depending on offset
3. From SEEK_END (-5):
Output: The 5th character before the file ends. For example: 'i' from "file."

Constants:

Constant Description

SEEK_SET Start from the beginning of the file. Offset is from byte 0.

SEEK_CUR Start from the current position of the file pointer.


SEEK_END Start from the end of the file. Offset should usually be negative.

Working with Binary Data

Example of writing and reading binary files:

struct Student {
char name[50];
int age;
};

struct Student s1 = {"Maria", 20};

// Writing to binary file


FILE *fp = fopen("student.dat", "wb");
fwrite(&s1, sizeof(s1), 1, fp);
fclose(fp);

// Reading from binary file


struct Student s2;
fp = fopen("student.dat", "rb");
fread(&s2, sizeof(s2), 1, fp);
fclose(fp);

You might also like