Input output and File Handling

By Notes Vandar

Input output and File Handling

In C, input and output operations are fundamental for interacting with users and handling data files.

7.1 Concept of File handling

File handling in C involves using a set of functions to perform operations on files such as creating, reading, writing, and closing them. Here’s a detailed overview of the key concepts and functions involved in file handling:

1. File Pointers

A file pointer is a variable of type FILE that is used to access files. It is returned by functions like fopen and used in other file handling functions.

Declaration:

FILE *filePointer;

2. Opening a File

The fopen function is used to open a file and returns a file pointer. If the file cannot be opened, it returns NULL.

Syntax:

FILE *fopen(const char *filename, const char *mode);
  • filename: The name of the file to be opened.
  • mode: The mode in which to open the file. Common modes include:
    • "r": Read-only mode.
    • "w": Write-only mode (creates a new file or truncates an existing file).
    • "a": Append mode (writes data to the end of the file).
    • "r+": Read and write mode.
    • "w+": Read and write mode (creates or truncates the file).
    • "a+": Read and write mode (appends to the end of the file).

Example:

FILE *file = fopen(“example.txt”, “w”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}

3. Writing to a File

To write data to a file, you can use functions like fprintf, fwrite, or fputs.

Examples:

  • fprintf: Writes formatted output.
    fprintf(file, “Hello, World!\n”);
  • fwrite: Writes binary data.
    int data = 123;
    fwrite(&data, sizeof(int), 1, file);
  • fputs: Writes a string.
    fputs(“Hello, World!\n”, file);

4. Reading from a File

To read data from a file, use functions like fscanf, fread, or fgets.

Examples:

  • fscanf: Reads formatted input.
    int num;
    fscanf(file, “%d”, &num);
  • fread: Reads binary data.
    int data;
    fread(&data, sizeof(int), 1, file);
  • fgets: Reads a string.
    char buffer[100];
    fgets(buffer, sizeof(buffer), file);

5. Closing a File

After completing file operations, it’s important to close the file using fclose. This frees up resources and ensures that all data is properly written to the file.

Syntax:

int fclose(FILE *stream);

Example:

fclose(file);

6. File Error Handling

To check for errors in file operations, use functions like ferror and clearerr.

  • ferror: Returns a non-zero value if an error has occurred.
    if (ferror(file)) {
    printf(“Error reading from file.\n”);
    }
  • clearerr: Clears the error indicators.
    clearerr(file);

7. File Positioning

You can move the file position indicator using functions like fseek, ftell, and rewind.

  • fseek: Moves the file position indicator to a specific location.
    fseek(file, 0, SEEK_SET); // Move to the beginning of the file
  • ftell: Returns the current position of the file indicator.
    long pos = ftell(file);
  • rewind: Moves the file position indicator to the beginning.
    rewind(file);

7.2 File Access methods

In C, file access methods refer to the ways you can read from and write to files. These methods determine how you interact with the file’s data. Here’s a breakdown of the common file access methods:

1. Sequential Access

Sequential access means reading or writing data in a linear fashion, from the beginning of the file to the end. This is the simplest and most common form of file access.

Example:

  • Reading Sequentially:

    FILE *file = fopen(“example.txt”, “r”);
    if (file == NULL) {
    printf(“Error opening file.\n”);
    return 1;
    }

    char buffer[100];
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
    printf(“%s”, buffer);
    }

    fclose(file);

  • Writing Sequentially:

    FILE *file = fopen(“example.txt”, “w”);
    if (file == NULL) {
    printf(“Error opening file.\n”);
    return 1;
    }

    fprintf(file, “Hello, World!\n”);
    fputs(“Welcome to file handling in C.\n”, file);

    fclose(file);

2. Random Access

Random access allows you to read from or write to a file at any location, not necessarily sequentially. This is useful for tasks where you need to access specific parts of the file directly.

Functions Used:

  • fseek: Moves the file position indicator to a specific location.
  • ftell: Returns the current file position.
  • rewind: Resets the file position indicator to the beginning of the file.

Example:

FILE *file = fopen(“example.dat”, “r+”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}

// Move to the 10th byte from the beginning
fseek(file, 10, SEEK_SET);

char buffer[100];
fread(buffer, sizeof(char), sizeof(buffer), file);
printf(“Data at position 10: %s\n”, buffer);

// Move back to the beginning
rewind(file);

// Write data at the beginning
fprintf(file, “Start of file data.\n”);

fclose(file);

3. Direct Access

Direct access (also known as indexed access) involves accessing a specific record or data element directly, based on its index or position. This method is often used in conjunction with binary files.

Example:

  • Writing Binary Data:

    FILE *file = fopen(“example.bin”, “wb”);
    if (file == NULL) {
    printf(“Error opening file.\n”);
    return 1;
    }

    int data = 1234;
    fwrite(&data, sizeof(int), 1, file);

    fclose(file);

  • Reading Binary Data:

    FILE *file = fopen(“example.bin”, “rb”);
    if (file == NULL) {
    printf(“Error opening file.\n”);
    return 1;
    }

    int data;
    fread(&data, sizeof(int), 1, file);
    printf(“Read data: %d\n”, data);

    fclose(file);

4. File Modes

When opening a file, the mode you choose affects how you can access the file:

  • "r": Open for reading (file must exist).
  • "w": Open for writing (creates a new file or truncates an existing file).
  • "a": Open for appending (writes data to the end of the file).
  • "r+": Open for reading and writing (file must exist).
  • "w+": Open for reading and writing (creates a new file or truncates an existing file).
  • "a+": Open for reading and writing (appends data to the end of the file).

7.3 Functions of file handling: fopen(), fclose(), fflush(), freopen()

In C, file handling functions are essential for managing files and performing operations like opening, closing, and manipulating file streams. Here’s a detailed look at some key file handling functions:

1. fopen()

Purpose: Opens a file and associates a file stream with it.

Syntax:

FILE *fopen(const char *filename, const char *mode);
  • filename: The name of the file to be opened.
  • mode: The mode in which to open the file (e.g., "r" for read, "w" for write, "a" for append).

Modes:

  • "r": Open for reading. The file must exist.
  • "w": Open for writing. Creates a new file or truncates an existing file.
  • "a": Open for appending. Data is written to the end of the file.
  • "r+": Open for reading and writing. The file must exist.
  • "w+": Open for reading and writing. Creates a new file or truncates an existing file.
  • "a+": Open for reading and writing. Appends data to the end of the file.

Example:

FILE *file = fopen(“example.txt”, “w”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
fprintf(file, “Hello, World!\n”);
fclose(file);

2. fclose()

Purpose: Closes an open file associated with a file pointer. It flushes the output buffer and deallocates resources associated with the file.

Syntax:

int fclose(FILE *stream);
  • stream: The file pointer to the file to be closed.

Return Value:

  • Returns 0 if successful.
  • Returns EOF if an error occurs.

Example:

FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fprintf(file, “Hello, World!\n”);
fclose(file); // Close the file
}

3. fflush()

Purpose: Flushes the output buffer of a stream, forcing all buffered data to be written to the file. This is useful when you want to ensure that all data written to a file is actually saved immediately.

Syntax:

int fflush(FILE *stream);
  • stream: The file pointer associated with the stream to be flushed.

Return Value:

  • Returns 0 if successful.
  • Returns EOF if an error occurs.

Example:

FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fprintf(file, “Hello, World!\n”);
fflush(file); // Flush the output buffer to ensure data is written to the file
fclose(file);
}

4. freopen()

Purpose: Reopens an existing file stream with a new file or mode. This function is often used to redirect input or output streams.

Syntax:

FILE *freopen(const char *filename, const char *mode, FILE *stream);
  • filename: The name of the file to open.
  • mode: The mode in which to open the file (e.g., "r", "w", "a").
  • stream: The existing file pointer to be associated with the new file.

Return Value:

  • Returns the file pointer on success.
  • Returns NULL on failure.

Example:

FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fprintf(file, “This will be written to example.txt\n”);
fclose(file);
}

FILE *newFile = freopen(“newfile.txt”, “w”, file);
if (newFile != NULL) {
fprintf(newFile, “This will be written to newfile.txt\n”);
fclose(newFile);
}

7.4 Formatted input out

Formatted input and output in C involve using functions that allow you to read and write data in a specific format. These functions are part of the C standard library and are used for handling text data with formatting requirements.

Formatted Output

1. printf()

The printf function is used for formatted output. It allows you to print variables and constants to the console with specified formatting.

Syntax:

int printf(const char *format, …);
  • format: A format string that specifies how subsequent arguments are converted for output.
  • ...: A variable number of arguments that are formatted according to the format string.

Format Specifiers:

  • %d or %i: Integer
  • %f: Floating-point number
  • %s: String
  • %c: Character
  • %x or %X: Hexadecimal integer

Example:

#include <stdio.h>

int main() {
int age = 25;
float height = 5.9;
char name[] = “Alice”;

printf(“Name: %s\n”, name);
printf(“Age: %d\n”, age);
printf(“Height: %.1f\n”, height);

return 0;
}

Special Formatting:

  • Width and Precision: Control the width and precision of the output.
    • %5d : Integer with a width of 5 characters.
    • %.2f : Floating-point number with 2 decimal places.
    • %10s : String with a minimum width of 10 characters.

Example:

#include <stdio.h>

int main() {
int num = 42;
printf(“Number: %5d\n”, num); // Right-aligned within 5 characters
printf(“Float: %.3f\n”, 3.14159); // 3 decimal places

return 0;
}

Formatted Input

1. scanf()

The scanf function is used for formatted input. It reads data from the standard input (usually the keyboard) and stores it in variables according to the specified format.

Syntax:

int scanf(const char *format, …);
  • format: A format string that specifies how input data is interpreted.
  • ...: Pointers to variables where the input data will be stored.

Format Specifiers:

  • %d or %i: Integer
  • %f: Floating-point number
  • %s: String (reads until whitespace)
  • %c: Character

Example:

#include <stdio.h>

int main() {
int age;
float height;
char name[50];

printf(“Enter your name: “);
scanf(“%s”, name); // Read a string (up to whitespace)

printf(“Enter your age: “);
scanf(“%d”, &age); // Read an integer

printf(“Enter your height: “);
scanf(“%f”, &height); // Read a floating-point number

printf(“Name: %s\n”, name);
printf(“Age: %d\n”, age);
printf(“Height: %.1f\n”, height);

return 0;
}

Special Input Handling:

  • Width Specifier: Limits the number of characters read for a string.
    • %10s : Read up to 10 characters into a string.
  • Character Input: scanf reads single characters including whitespace.
    • %c : Read a single character.

Example:

#include <stdio.h>

int main() {
char str[10];
printf(“Enter a string (max 9 characters): “);
scanf(“%9s”, str); // Read up to 9 characters (leave space for null terminator)

printf(“You entered: %s\n”, str);

return 0;
}

7.5 Character input output

In C, character input and output involve functions that handle individual characters rather than strings or formatted data. These functions are part of the C standard library and allow you to read and write characters directly.

Character Output

1. putchar()

The putchar function is used to write a single character to the standard output (usually the console).

Syntax:

int putchar(int char);
  • char: The character to be written.

Return Value: Returns the character written as an unsigned char cast to an int or EOF on error.

Example:

#include <stdio.h>

int main() {
char c = ‘A’;
putchar(c); // Output: A
putchar(‘\n’); // Output: newline character
return 0;
}

2. fputc()

The fputc function writes a single character to a specified file stream.

Syntax:

int fputc(int char, FILE *stream);
  • char: The character to be written.
  • stream: The file pointer to the file where the character will be written.

Return Value: Returns the character written as an unsigned char cast to an int or EOF on error.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fputc(‘H’, file); // Write ‘H’ to the file
fclose(file);
}
return 0;
}

Character Input

1. getchar()

The getchar function reads a single character from the standard input (usually the keyboard).

Syntax:

int getchar(void);

Return Value: Returns the character read as an unsigned char cast to an int, or EOF on end-of-file or error.

Example:

#include <stdio.h>

int main() {
char c;
printf(“Enter a character: “);
c = getchar(); // Read a character from standard input
printf(“You entered: “);
putchar(c); // Output the character
putchar(‘\n’);
return 0;
}

2. fgetc()

The fgetc function reads a single character from a specified file stream.

Syntax:

int fgetc(FILE *stream);
  • stream: The file pointer from which the character will be read.

Return Value: Returns the character read as an unsigned char cast to an int, or EOF on end-of-file or error.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “r”);
if (file != NULL) {
int c = fgetc(file); // Read a character from the file
if (c != EOF) {
putchar(c); // Output the character
}
fclose(file);
}
return 0;
}

7.6 Direct input output

In C, direct input and output (I/O) generally refer to handling data in a way that allows precise control over how data is read from or written to files. This involves working with binary files and using functions that interact with data at a more granular level compared to formatted text I/O.

Direct I/O Operations

Direct I/O typically involves reading and writing data in binary format, which is more efficient and flexible for certain applications compared to text-based I/O.

1. Binary File I/O

Binary files store data in a format that is directly readable by the program, rather than as human-readable text. This allows for more compact and efficient data storage.

a. Writing Binary Data

Use fwrite to write binary data to a file.

Syntax:

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
  • ptr: Pointer to the data to be written.
  • size: Size of each item to write.
  • count: Number of items to write.
  • stream: File pointer to the file.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “wb”);
if (file != NULL) {
int data = 12345;Add New Media File
fwrite(&data, sizeof(int), 1, file); // Write integer to file
fclose(file);
}
return 0;
}

b. Reading Binary Data

Use fread to read binary data from a file.

Syntax:

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
  • ptr: Pointer to buffer where the data will be read.
  • size: Size of each item to read.
  • count: Number of items to read.
  • stream: File pointer to the file.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “rb”);
if (file != NULL) {
int data;
fread(&data, sizeof(int), 1, file); // Read integer from file
printf(“Data read: %d\n”, data);
fclose(file);
}
return 0;
}

2. File Positioning

Direct I/O often involves manipulating the file position indicator to read or write data at specific locations in the file.

a. fseek()

Moves the file position indicator to a specified location.

Syntax:

int fseek(FILE *stream, long offset, int whence);
  • stream: File pointer to the file.
  • offset: Number of bytes to move from the reference point.
  • whence: Reference point (SEEK_SET, SEEK_CUR, SEEK_END).

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “rb+”);
if (file != NULL) {
fseek(file, 0, SEEK_SET); // Move to the beginning of the file
int data = 54321;
fwrite(&data, sizeof(int), 1, file); // Overwrite data at the beginning
fclose(file);
}
return 0;
}

b. ftell()

Returns the current position of the file indicator.

Syntax:

long ftell(FILE *stream);

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “rb”);
if (file != NULL) {
fseek(file, 0, SEEK_END); // Move to the end of the file
long size = ftell(file); // Get the file size
printf(“File size: %ld bytes\n”, size);
fclose(file);
}
return 0;
}

c. rewind()

Resets the file position indicator to the beginning of the file.

Syntax:

void rewind(FILE *stream);

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “rb”);
if (file != NULL) {
rewind(file); // Reset position to the beginning
int data;
fread(&data, sizeof(int), 1, file); // Read data from the beginning
printf(“Data read after rewind: %d\n”, data);
fclose(file);
}
return 0;
}

7.7 Random file access

Random file access, or direct file access, refers to the ability to read from or write to a file at arbitrary locations, rather than sequentially from start to end. This capability is particularly useful when you need to efficiently access or modify specific parts of a file without processing the entire file.

Key Concepts

  1. File Position Indicator: The file position indicator keeps track of where the next read or write operation will occur. Functions like fseek() and ftell() are used to manipulate and query this position.
  2. Binary Files: Random access is typically used with binary files, where data is stored in a format that can be read and written efficiently. In contrast, text files are usually processed sequentially.

Functions for Random File Access

1. fseek()

The fseek() function moves the file position indicator to a specified location in the file. It is used to set the position for subsequent read or write operations.

Syntax:

int fseek(FILE *stream, long offset, int whence);
  • stream: File pointer to the file.
  • offset: Number of bytes to move from the reference point.
  • whence: Reference point (SEEK_SET, SEEK_CUR, SEEK_END).

Return Value: Returns 0 if successful; otherwise, returns -1.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “r+”);
if (file != NULL) {
fseek(file, 10, SEEK_SET); // Move to the 10th byte from the beginning
fwrite(“Hello”, 1, 5, file); // Write “Hello” at that position
fclose(file);
}
return 0;
}

2. ftell()

The ftell() function returns the current position of the file position indicator. This is useful for determining the current position after a fseek() operation.

Syntax:

long ftell(FILE *stream);

Return Value: Returns the current position in the file, or -1L if an error occurs.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “r”);
if (file != NULL) {
fseek(file, 0, SEEK_END); // Move to the end of the file
long size = ftell(file); // Get the file size
printf(“File size: %ld bytes\n”, size);
fclose(file);
}
return 0;
}

3. rewind()

The rewind() function resets the file position indicator to the beginning of the file. It is a convenient way to return to the start of the file.

Syntax:

void rewind(FILE *stream);

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “r”);
if (file != NULL) {
fseek(file, 10, SEEK_SET); // Move to a specific position
// Perform operations
rewind(file); // Return to the beginning
// Perform operations from the start
fclose(file);
}
return 0;
}

Example of Random File Access

Here’s a complete example that demonstrates random file access by writing and then reading from specific locations in a binary file:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “w+b”);
if (file != NULL) {
int data = 12345;

// Write data to different positions
fseek(file, 0, SEEK_SET);
fwrite(&data, sizeof(int), 1, file);

data = 67890;
fseek(file, sizeof(int), SEEK_SET); // Move to the position after the first integer
fwrite(&data, sizeof(int), 1, file);

// Read the data back
fseek(file, 0, SEEK_SET);
fread(&data, sizeof(int), 1, file);
printf(“First integer: %d\n”, data);

fseek(file, sizeof(int), SEEK_SET);
fread(&data, sizeof(int), 1, file);
printf(“Second integer: %d\n”, data);

fclose(file);
}
return 0;
}

7.8 Error handling

Error handling in file operations is crucial for writing robust and reliable programs. In C, several standard library functions provide ways to detect and handle errors that occur during file operations. Here’s a detailed overview of error handling in file I/O:

Error Detection and Handling Functions

1. ferror()

The ferror() function checks if an error has occurred on a given file stream. It returns a non-zero value if an error has occurred, and 0 otherwise.

Syntax:

int ferror(FILE *stream);
  • stream: File pointer to the file stream.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“nonexistent_file.txt”, “r”);
if (file == NULL) {
perror(“Error opening file”);
return 1;
}

// Attempt to read from the file
char buffer[100];
if (fread(buffer, sizeof(char), 100, file) < 100) {
if (ferror(file)) {
perror(“Error reading file”);
}
}

fclose(file);
return 0;
}

2. clearerr()

The clearerr() function clears the error and end-of-file indicators for the specified stream. This allows further operations on the stream to proceed as if no error had occurred.

Syntax:

void clearerr(FILE *stream);
  • stream: File pointer to the file stream.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “r”);
if (file == NULL) {
perror(“Error opening file”);
return 1;
}

// Attempt to read from the file
char buffer[100];
if (fread(buffer, sizeof(char), 100, file) < 100) {
if (ferror(file)) {
perror(“Error reading file”);
clearerr(file); // Clear the error state
}
}

fclose(file);
return 0;
}

3. perror()

The perror() function prints a descriptive error message to stderr. It provides information about the most recent error that occurred during a library function call, using the global variable errno.

Syntax:

void perror(const char *s);
  • s: A string to be printed before the error message.

Example:

#include <stdio.h>
#include <errno.h>

int main() {
FILE *file = fopen(“nonexistent_file.txt”, “r”);
if (file == NULL) {
perror(“Error opening file”);
return 1;
}

fclose(file);
return 0;
}

Error Codes

Error codes are provided by the global variable errno, which is set by system calls and library functions to indicate the specific type of error.

Common Error Codes:

  • ENOENT: No such file or directory.
  • EACCES: Permission denied.
  • ENOMEM: Not enough memory.
  • EIO: Input/output error.

Example Using errno:

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
FILE *file = fopen(“nonexistent_file.txt”, “r”);
if (file == NULL) {
printf(“Error opening file: %s\n”, strerror(errno));
return 1;
}

fclose(file);
return 0;
}

7.9 File operation

File operations in C involve performing various tasks with files, such as creating, opening, reading, writing, and closing them. Understanding these operations is crucial for effective file management in your programs. Here’s an overview of the key file operations:

1. Opening and Creating Files

fopen() is used to open a file or create a new file if it doesn’t exist. The function returns a file pointer that you use for subsequent file operations.

Syntax:

FILE *fopen(const char *filename, const char *mode);
  • filename: Name of the file to be opened or created.
  • mode: Mode in which to open the file ("r", "w", "a", etc.).

Common Modes:

  • "r": Open for reading. File must exist.
  • "w": Open for writing. Creates a new file or truncates an existing file.
  • "a": Open for appending. Creates a new file or appends to an existing file.
  • "r+": Open for reading and writing. File must exist.
  • "w+": Open for reading and writing. Creates a new file or truncates an existing file.
  • "a+": Open for reading and appending. Creates a new file or appends to an existing file.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
// File operations
fclose(file);
} else {
perror(“Error opening file”);
}
return 0;
}

2. Closing Files

fclose() closes a file that was opened with fopen(). It is important to close files to free up system resources.

Syntax:

int fclose(FILE *stream);

Return Value: Returns 0 if successful; otherwise, returns EOF.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
// File operations
fclose(file);
}
return 0;
}

3. Reading and Writing Data

a. Writing Data

  • fprintf(): Formats and writes data to a file stream.

Syntax:

int fprintf(FILE *stream, const char *format, …);
  • fwrite(): Writes binary data to a file.

Syntax:

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

Examples:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fprintf(file, “Hello, world!\n”);

int numbers[] = {1, 2, 3, 4, 5};
fwrite(numbers, sizeof(int), 5, file);

fclose(file);
}
return 0;
}

b. Reading Data

  • fscanf(): Reads formatted data from a file stream.

Syntax:

int fscanf(FILE *stream, const char *format, …);
  • fread(): Reads binary data from a file.

Syntax:

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

Examples:

#include <stdio.h>

int main() {
FILE *file = fopen(“example.txt”, “r”);
if (file != NULL) {
char buffer[100];
if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf(“Read line: %s”, buffer);
}

int numbers[5];
fread(numbers, sizeof(int), 5, file);
for (int i = 0; i < 5; i++) {
printf(“Number: %d\n”, numbers[i]);
}

fclose(file);
}
return 0;
}

4. File Positioning

a. fseek(): Moves the file position indicator to a specific location.

int fseek(FILE *stream, long offset, int whence);

b. ftell(): Returns the current position of the file indicator.

Syntax:

long ftell(FILE *stream);

c. rewind(): Resets the file position indicator to the beginning of the file.

Syntax:

void rewind(FILE *stream);

5. File Operations Example

Here is an example that combines various file operations including opening, writing, reading, and closing a file:

#include <stdio.h>

int main() {
FILE *file = fopen(“data.bin”, “wb”);
if (file != NULL) {
int numbers[5] = {1, 2, 3, 4, 5};
fwrite(numbers, sizeof(int), 5, file); // Write integers to the file
fclose(file); // Close the file
}

file = fopen(“data.bin”, “rb”);
if (file != NULL) {
int numbers[5];
fread(numbers, sizeof(int), 5, file); // Read integers from the file
for (int i = 0; i < 5; i++) {
printf(“Number %d: %d\n”, i+1, numbers[i]);
}
fclose(file); // Close the file
}

return 0;
}

Important Questions
Comments
Discussion
0 Comments
  Loading . . .