0% found this document useful (0 votes)
27 views7 pages

C File Handling and Preprocessor Guide

The document explains file handling in C, detailing how to read from and write to files using various File I/O functions like fopen(), fclose(), fprintf(), and fgets(). It also covers the use of the C preprocessor for defining macros and handling command-line arguments in the main() function. Key concepts include the syntax for file operations, macro definitions, and the structure of command-line arguments.
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)
27 views7 pages

C File Handling and Preprocessor Guide

The document explains file handling in C, detailing how to read from and write to files using various File I/O functions like fopen(), fclose(), fprintf(), and fgets(). It also covers the use of the C preprocessor for defining macros and handling command-line arguments in the main() function. Key concepts include the syntax for file operations, macro definitions, and the structure of command-line arguments.
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

File handling in C allows programs to store data permanently on a disk, unlike standard

I/O which is temporary in memory. This functionality relies on specific File I/O
Functions and the Standard C Preprocessor directive #include <stdio.h> .

#include <stdio.h>
#include <stdlib.h> // Required for exit()
int main() {
FILE *fp;
char name[50];
int age;
int num_students = 2;
// --- WRITING DATA TO A FILE ---
// Open the file in write mode ("w")
// If the file does not exist, it will be created.
// If it exists, its previous content will be overwritten.
fp = fopen("[Link]", "w");
// Check if the file opened successfully
if (fp == NULL) {
printf("Error opening file for writing!\n");
// Use exit() to terminate the program if file cannot be opened
exit(1);
}
printf("Writing student data to '[Link]'...\n");
// Write data into the file using fprintf()
fprintf(fp, "Name: Alice, Age: 25\n");
fprintf(fp, "Name: Bob, Age: 30\n");
// Close the file after writing
fclose(fp);
printf("Successfully wrote data and closed file.\n\n");
// --- READING DATA FROM A FILE ---
// Open the file in read mode ("r")
fp = fopen("[Link]", "r");
// Check if the file opened successfully
if (fp == NULL) {
printf("Error opening file for reading!\n");
exit(1);
}
printf("Reading data from '[Link]':\n");
char line[100]; // Buffer to hold each line read from the file
// Use a while loop and fgets() to read data line by line until the end of the file
// fgets returns NULL when it reaches the end of the file (EOF) or an error occurs.
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line); // Print the line read from the file
}
// Close the file after reading
fclose(fp);
printf("\nSuccessfully read data and closed file.\n");
return 0;
}

File Handling: File I/O Functions


All file handling operations in C are performed using a special pointer of type FILE * ,
often named fp or fptr , which connects the program to the file stream.

Core File Operations and Functions

Function Description Common Use

fopen() Opens an existing file or creates a new one in a specified Starting file operations
mode (e.g., "r" , "w" , "a" , "rb" ). Returns a FILE
* pointer or NULL if it fails.

fclose() Closes an opened file stream, flushes any pending data, and Safely ending file
frees resources. operations

fprintf() Writes formatted data to a file, similar to printf() . Writing strings,


numbers, variables to
text files

fscanf() Reads formatted data from a file, similar to scanf() . Reading structured
content from text files
fgetc() Reads a single character from a file. Reading character-by-
character

fputc() Writes a single character to a file. Writing individual


characters

fgets() Reads a line (string) from a file. Reading lines of text

fputs() Writes a string to a file (without format specifiers). Writing plain strings

fread() Reads a block of raw binary data from a file. Reading structures or
arrays from binary
files

fwrite() Writes a block of raw binary data to a file. Writing structures or


arrays to binary files

fseek() Sets the position of the file pointer to a specific location. Random access
within a file

rewind() Resets the file pointer to the beginning of the file. Restarting file
reading/writing

feof() Checks if the end of the file has been reached, returning a Error and end-of-file
non-zero value at the end. checking

Standard C Preprocessors
The C preprocessor is a text substitution tool that processes the source code before the
actual compilation begins. All preprocessor commands, called directives, start with the
hash symbol ( # ).

Key Preprocessor Directives


 #include : Inserts the entire content of a specified header file into the current file.

o #include <filename.h> : Used for standard library files (e.g., <stdio.h> ).


o #include "filename.h" : Used for user-defined header files, often searched for in the

current directory.
 #define : Defines a macro, which is a symbolic name or expression that the

preprocessor replaces with its defined value throughout the code.


o Example: #define PI 3.14159 replaces all occurrences of PI with 3.14159 .

 Conditional Compilation: Directives like #if , #else , #elif , #ifdef , #ifndef ,


and #endif allow certain blocks of code to be compiled only if specific conditions are
met (e.g., for debugging or platform-specific code).
 #undef : Undefines a previously defined macro.

 #error : Stops compilation and displays a custom error message.

 #pragma : Provides specific instructions to the compiler (compiler-specific).

In C programming, macros are defined using the #define preprocessor directive and
are "called" or expanded by the preprocessor during a text substitution phase before
compilation. Command-line arguments, on the other hand, are values passed to
the main() function when the compiled program is executed at runtime.

Defining and Calling Macros


Macros are essentially shorthand for code or values. They are handled by the C
preprocessor, not the compiler itself.

Defining Macros
You use the #define directive, typically at the beginning of a source file or in a header
file. The syntax is:

c
#define MACRO_NAME replacement_text

 Object-like macros are used for simple constant values.

c
#define PI 3.14159
#define LIMIT 100
 Function-like macros take arguments and behave like functions, but without the
overhead of a function call.

c
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))

Note: It's best practice to enclose arguments and the entire macro body in parentheses
to avoid operator precedence issues.
Calling (Invoking) Macros
A macro is "called" simply by using its name in the source code. The preprocessor
replaces every instance of the macro name with its defined text before compilation.

 Object-like macro call:

c
float area = PI * radius * radius;
// Expands to: float area = 3.14159 * radius * radius;

 Function-like macro call:

c
int num = 4;
int squared = SQUARE(num);
// Expands to: int squared = ((num) * (num));

You can also define macros on the command line using the compiler's -D flag
(e.g., gcc -DDEBUG=1 or cl /DDEBUG=1 ). This is useful for conditional compilation,
such as toggling debug features without editing the source code.

Command-Line Arguments
Command-line arguments allow you to pass inputs to your program when you execute it
from the terminal. These arguments are managed by the main() function.

How to Use
The standard signature for the main() function to accept command-line arguments is:
c
int main(int argc, char *argv[])

 argc (argument count) is an integer that stores the total number of arguments,

including the program's name. Its value is always at least 1.


 argv (argument vector) is an array of character pointers (strings), where each

element points to a command-line argument.


o argv[0] is always the name used to invoke the program.

o argv[1] is the first actual argument provided by the user.

o argv[argc - 1] is the last argument.

o argv[argc] is a NULL pointer.

Example Program
This C program prints all command-line arguments it receives:

c
#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Total arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}

Calling with Arguments


1. Compile the program (assuming the file is named argsdemo.c ):

bash
gcc argsdemo.c -o argsdemo

2. Run the program with arguments:

bash
./argsdemo apple mango banana

3. Output would be:

4. Total arguments: 4
5. Argument 0: ./argsdemo
6. Argument 1: apple
7. Argument 2: mango
Argument 3: banana

You might also like