Unit 2 - Part2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

1.

File Handling

A file refers to a source in which a program stores the information/data in the form of bytes of
sequence on a disk (permanently). The content available on a file isn’t volatile like the compiler
memory in C. But the program can perform various operations, such as creating, opening,
reading a file, or even manipulating the data present inside the file.
The following operations can be performed on a file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file. A list of
file functions are given below:
Function Description
fopen() opens new or existing file
fprintf() write data into the file
fscanf() reads data from the file
fputc() writes a character into the file
fgetc() reads a character from file
fclose() closes the file
1. Creation of a New File
To create a new file or open an existing file (and truncate it if it already exists), you use the
fopen() function with the "w" mode. This mode opens the file for writing and creates the file if it
does not exist.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("newfile.txt", "w"); // Open file for writing (create if not exists)
if (file == NULL) {
perror("Error creating file");
return 1;

1
}
// File is successfully created and opened
fprintf(file, "This is a new file.\n"); // Write to the file
fclose(file); // Close the file
return 0;
}
Explanation:
fopen("newfile.txt", "w") creates newfile.txt if it doesn't exist or truncates it if it does.
fprintf(file, "This is a new file.\n"); writes a line of text to the file.
fclose(file); closes the file.

2. Opening an Existing File


To open an existing file for reading or writing, you use the fopen() function with the
appropriate mode.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("newfile.txt", "r"); // Open file for reading
if (file == NULL) {
perror("Error opening file for reading");
return 1;
}
// File is successfully opened for reading
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer); // Print each line read from the file
}
fclose(file); // Close the file
return 0;
}
Explanation:
fopen("newfile.txt", "r") opens newfile.txt for reading. The file must exist.
fgets(buffer, sizeof(buffer), file) reads lines from the file into buffer.
fclose(file); closes the file.
3. Reading from the File
Reading from a file can be done using fgetc(), fgets(), or fread(), depending on the type of data.

2
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("newfile.txt", "r"); // Open file for reading
if (file == NULL) {
perror("Error opening file for reading");
return 1;
}
charch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print each character read from the file
}
fclose(file); // Close the file
return 0; }
Explanation:
fgetc(file) reads a single character from the file.
putchar(ch) prints the character to the standard output.
EOF signifies the end of the file.
4. Writing to the File
To write data to a file, use fprintf(), fputs(), or fputc().
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("newfile.txt", "a"); // Open file for appending
if (file == NULL) {
perror("Error opening file for appending");
return 1;
}

// Append data to the file


fprintf(file, "Appending more text.\n"); // Write formatted text
fputs("Another line appended.\n", file); // Write a string
fputc('X', file); // Write a single character

fclose(file); // Close the file


return 0;
}
Explanation:

3
fopen("newfile.txt", "a") opens newfile.txt for appending. If the file does not exist, it will
be created.
fprintf(file, "Appending more text.\n"); writes formatted text to the file.
fputs("Another line appended.\n", file); writes a string to the file.
fputc('X', file); writes a single character to the file.
fclose(file); closes the file.
5. Deleting the File
To delete a file, use the remove() function. This function removes the file specified by its
name.
Example:
#include <stdio.h>
int main() {
// Delete a file
if (remove("newfile.txt") == 0) {
printf("File successfully deleted.\n");
} else {
perror("Error deleting file");
}
return 0;
}
Explanation:
remove("newfile.txt") deletes the file newfile.txt.
If successful, it prints a success message. Otherwise, it prints an error message.
Example for File Handling
#include <stdio.h>
int main() {
FILE *file;
const char *filename = "example.txt";

// Write data to the file


file = fopen(filename, "w"); // Open file in write mode
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
4
}
fprintf(file, "Hello, world!\n");
fprintf(file, "This is a simple file handling example.\n");
fclose(file); // Close the file

// Read data from the file


file = fopen(filename, "r"); // Open file in read mode
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
char buffer[256]; // Buffer to hold file content
printf("File Content After Writing:\n");
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file); // Close the file

// Append data to the file


file = fopen(filename, "a"); // Open file in append mode
if (file == NULL) {
printf("Error opening file for appending.\n");
return 1;
}
fprintf(file, "Appending new content to the file.\n");
fclose(file); // Close the file

// Read data from the file again to see the appended content
file = fopen(filename, "r"); // Open file in read mode
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
printf("File Content After Appending:\n");
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file); // Close the file

return 0;
5
}
2. Preprocessor Directives
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess
the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash)
symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the
preprocessor program to get executed. We can place these preprocessor directives anywhere
in our program.
Examples of some preprocessor directives are: #include, #define, #ifndef, etc.

List of preprocessor directives in C

The following table lists all the preprocessor directives in C:

Preprocessor
Directives Description

#define Used to define a macro

#undef Used to undefine a macro

Used to include a file in the source code


#include
program

Used to include a section of code if a


#ifdef
certain macro is defined by #define

Used to include a section of code if a


#ifndef
certain macro is not defined by #define
6
Preprocessor
Directives Description

#if Check for the specified condition

#else Alternate code that executes when #if fails

Used to mark the end of #if, #ifdef, and


#endif
#ifndef
Types of C Preprocessors
There are 4 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
1. Macros
In C, Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of code. The
‘#define’ directive is used to define a macro.

Syntax of Macro Definition: #define token value


where after preprocessing, the token will be expanded to its value in the program.
Example of Macro
#define PI 3.14159
#define BUFFER_SIZE 1024
Example Program
#include <stdio.h>
#define LIMIT 5 // macro definition
int main()
{
for (inti = 0; i< LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
Output :0 1 2 3 4

2. File Inclusion
7
File inclusion directives are used to include the contents of one file within another file. This is
commonly used to include header files.
Standard Library Headers: Includes system or standard library headers.
#include <stdio.h>
#include <stdlib.h>

User-Defined Headers: Includes user-defined header files.


#include "myheader.h"

3. Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a specific
portion of the program or to skip the compilation of some specific part of the program based on
some conditions.There are the following preprocessor directives that are used to insert
conditional code:
#if Directive
#ifdef Directive
#ifndef Directive
#else Directive
#elif Directive
#endif Directive

******

You might also like