0% found this document useful (0 votes)
84 views8 pages

File Handling in C

It deals with how to create, open, wi=rite, read and append files using C language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views8 pages

File Handling in C

It deals with how to create, open, wi=rite, read and append files using C language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

File Handling in C

File handling in C is a powerful feature that allows you to read, write, and
manipulate files. Files are used to store data permanently on storage media, unlike
variables, which are stored in RAM and are lost when the program terminates. In
C, files are represented using pointers of type `FILE *`, which are defined in the
`<stdio.h>` header.

1. **Types of Files in C**

There are two primary types of files in C:

1. **Text Files**:
- These files store data in human-readable form (ASCII characters).
- Each line of text is terminated with a newline character (`\n`), and each word or
number is separated by spaces or other delimiters.

2. **Binary Files**:
- These files store data in a binary format (machine-readable form).
- They are used for storing complex data like images, audio, or other binary data
without any transformation to readable text.

2. **File Operations in C**

File handling in C involves various operations:


- **Creating** a file
- **Opening** a file
- **Reading** from a file
- **Writing** to a file
- **Closing** a file

3. **Opening a File in C**

The `fopen()` function is used to open a file. It returns a pointer of type `FILE*`
which points to the file stream.

#### Syntax:
FILE *fopen(const char *filename, const char *mode);

- **filename**: Name of the file (a string).


- **mode**: The mode in which the file is to be opened.

Modes for `fopen()`:


- `"r"`: Open a file for reading. The file must exist.
- `"w"`: Open a file for writing. If the file exists, it will be truncated (erased). If the
file does not exist, it will be created.
- `"a"`: Open a file for appending. Data is written at the end of the file. If the file
does not exist, it will be created.
- `"r+"`: Open a file for both reading and writing. The file must exist.
- `"w+"`: Open a file for both reading and writing. If the file exists, it will be
truncated. If the file does not exist, it will be created.
- `"a+"`: Open a file for both reading and appending. If the file does not exist, it
will be created.
Example of opening a file:
FILE *file_ptr = fopen("data.txt", "r");
if (file_ptr == NULL) {
printf("Error: Unable to open file.\n");
}

4. **Closing a File in C**

Once a file operation is completed, the file must be closed to free system resources.
The `fclose()` function is used to close a file.

Syntax:

int fclose(FILE *fp);

- **fp**: The file pointer returned by `fopen()`.

Example:

fclose(file_ptr);

5. **Reading from a File in C**


There are several functions available for reading data from a file. The method you
choose depends on the type of data you're working with.

Functions for reading text files:

- **fgetc()**: Reads a single character from a file.

int fgetc(FILE *fp);

Example:
char ch = fgetc(file_ptr);

- **fgets()**: Reads a string from a file. It reads up to `n-1` characters or until a


newline is encountered.

char *fgets(char *str, int n, FILE *fp);

Example:
char str[100];
fgets(str, 100, file_ptr);
printf("%s", str);

- **fscanf()**: Reads formatted input from a file, similar to `scanf()`.


int fscanf(FILE *fp, const char *format, ...);
Example:

int num;
fscanf(file_ptr, "%d", &num);

#### Functions for reading binary files:

- **fread()**: Reads blocks of data from a binary file.

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *fp);

- `ptr`: Pointer to where the read data will be stored.


- `size`: Size of each element to read (in bytes).
- `nmemb`: Number of elements to read.
- `fp`: File pointer.

Example:
int buffer[5];
fread(buffer, sizeof(int), 5, file_ptr);

6. **Writing to a File in C**


C provides several functions to write data to a file. The appropriate function
depends on whether you're working with text or binary data.

#### Functions for writing text files:

- **fputc()**: Writes a single character to a file.

int fputc(int ch, FILE *fp);

Example:

fputc('A', file_ptr);

- **fputs()**: Writes a string to a file.

int fputs(const char *str, FILE *fp);

Example:

fputs("Hello, World!", file_ptr);

- **fprintf()**: Writes formatted data to a file, similar to `printf()`.

int fprintf(FILE *fp, const char *format, ...);


Example:

int num = 42;


fprintf(file_ptr, "The number is %d\n", num);

5. **File Positioning Functions**

File positioning functions allow you to move the file pointer to a specific location
in the file.

- **fseek()**: Moves the file pointer to a specific position.

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

- `offset`: Number of bytes to move.


- `whence`: Starting point (`SEEK_SET` for beginning, `SEEK_CUR` for
current position, `SEEK_END` for end of the file).

Example:

fseek(file_ptr, 0, SEEK_SET); // Move file pointer to the beginning of the file


- **ftell()**: Returns the current position of the file pointer.

long ftell(FILE *fp);

Example:

long pos = ftell(file_ptr);


printf("Current position: %ld\n", pos);

You might also like