Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with Files in C Programming

Tech 2

In C, file operations are managed using a pointer variable that references a file, known as a file pointer. This is analogous to file objects in other languages like Java.

File Pointer Declaration

FILE *filePointer;

Opening Files with fopen The fopen function is used to open a file. Its syntax is:

filePointer = fopen("filename", "mode");
  • filePointer: A variable declared as FILE *.
  • filename: A string specifying the file name.
  • mode: A string indicating the file access type.

Closing Files with fclose After file operations, close the file with fclose to prevent data loss:

fclose(filePointer);
  • Returns 0 on success; non-zero indicates an error.

Example Workflow

  1. Include the standard I/O header:
#include <stdio.h>
  1. Declare a file pointer:
FILE *fp = NULL;
  1. Open a file:
fp = fopen("example.txt", "r");
if (fp == NULL) {
    printf("Error opening file.\n");
    exit(1);
}
  1. Perform file operations.
  2. Close the file:
fclose(fp);

File Access Modes

  • r: Read from an existing file.
  • w: Write to a new file; overwrites if exists.
  • a: Append to an existing file; creates if not exists.
  • r+: Read and write to an existing file.
  • w+: Read and write to a new file; overwrites if exists.
  • a+: Append and read from a file; creates if not exists.
  • t: Text file (default).
  • b: Binary file.

Key Points

  • Modes combine characters: r, w, a, t, b, +.
  • Use r only for existing files.
  • w creates or overwrites files.
  • a appends data; creates files if needed.
  • Check fopen return for NULL to handle errors.
  • Text files involve ASCII-binary conversion; binary files do not.
  • Standard streams (e.g., stdin, stdout) are pre-opened.

Character I/O Functions

  • fgetc: Reads a single character; returns EOF at end.
  • fputc: Writes a single character.

String I/O Functions

  • fgets: Reads a string up to a specified length or newline/EOF.
fgets(buffer, size, fp);
  • fputs: Writes a string; returns number of characters written.

Block I/O Functions

  • fread: Reads blocks of data.
fread(dataBuffer, elementSize, count, fp);
  • fwrite: Writes blocks of data.
fwrite(dataBuffer, elementSize, count, fp);

Formatted I/O Functions

  • fprintf: Writes formatted data to a file.
fprintf(fp, "%d %s", num, str);
  • fscanf: Reads formatted data from a file.
fscanf(fp, "%d %s", &num, str);

Random File Access Use rewind or fseek to move the file position pointer.

  • rewind(fp): Resets pointer to file start.
  • fseek(fp, offset, origin): Moves pointer relative to origin (0=start, 1=current, 2=end).
fseek(fp, 50L, SEEK_SET);
  • Best used with binary files due to text file conversion issues.

File Status Functiosn

  • feof(fp): Returns non-zero if end-of-file is reached.
  • ferror(fp): Checks for errors during file operations.
  • clearerr(fp): Clears error and end-of-file flags.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.