Ad Space
Text Files:
\n might be translated to a carriage return-line feed combination (\r\n) on Windows.fprintf(), fscanf(), fgetc(), fputc() are used.Binary Files:
fread() and fwrite() are used.Example (Writing/Reading a structure in Binary Mode):
#include <stdio.h>
struct Student {
int roll;
char name[50];
};
int main() {
FILE *fp;
struct Student s_write = {101, "Alice"};
struct Student s_read;
// --- Write to binary file ---
fp = fopen("student.dat", "wb"); // "wb" = write binary
if (fp == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
fwrite(&s_write, sizeof(struct Student), 1, fp);
fclose(fp);
printf("Wrote: %d, %s\n", s_write.roll, s_write.name);
// --- Read from binary file ---
fp = fopen("student.dat", "rb"); // "rb" = read binary
if (fp == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
fread(&s_read, sizeof(struct Student), 1, fp);
fclose(fp);
printf("Read: %d, %s\n", s_read.roll, s_read.name);
return 0;
}
(These questions are identical).
There are two main types of file processing (or file access) in C:
fgetc(), fputc(), fscanf(), and fprintf() use sequential access.fseek(): To move the file pointer to a specific location.ftell(): To get the current position of the file pointer.rewind(): To reset the file pointer to the beginning.(These questions are all related to basic file operations. This is a comprehensive answer.)
File handling in C involves several key operations to interact with files on the disk:
fopen()):
FILE *fp = fopen("filename.txt", "mode");"r": Read (file must exist)."w": Write (creates new file or truncates existing)."a": Append (adds to the end of the file; creates if not exist)."r+": Read and Write (file must exist)."w+": Read and Write (creates new or truncates)."a+": Read and Append (creates if not exist)."b" for binary mode (e.g., "rb", "wb").fscanf(fp, "...", ...): Reads formatted data (like scanf).fgetc(fp): Reads a single character.fgets(buffer, size, fp): Reads a line (string).fread(buffer, size, count, fp): Reads count blocks of size bytes (for binary files).fprintf(fp, "...", ...): Writes formatted data (like printf).fputc(char, fp): Writes a single character.fputs(buffer, fp): Writes a string.fwrite(buffer, size, count, fp): Writes count blocks of size bytes (for binary files).fclose()):
fclose(fp);Example (Write then Read):
#include <stdio.h>
int main() {
FILE *fp;
char text[100];
// 1. Write to file
fp = fopen("data.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "Hello World\n%d", 2025);
fclose(fp);
// 2. Read from file
fp = fopen("data.txt", "r");
if (fp == NULL) return 1;
fscanf(fp, "%s", text);
printf("Read string: %s\n", text);
int year;
fscanf(fp, "%d", &year);
printf("Read integer: %d\n", year);
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
FILE *sourceFile, *destFile;
char ch;
// Open the source file in read mode
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Error: Cannot open source file.\n");
exit(1);
}
// Open the destination file in write mode
destFile = fopen("destination.txt", "w");
if (destFile == NULL) {
printf("Error: Cannot open destination file.\n");
fclose(sourceFile);
exit(1);
}
// Read character by character from source
// and write to destination until EOF is reached.
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destFile);
}
printf("File copied successfully!\n");
// Close both files
fclose(sourceFile);
fclose(destFile);
return 0;
}
Random access (or direct access) allows a program to read or write data from any location in a file, without having to read through all the preceding data. This is essential for applications like databases. This is achieved using file-positioning functions:
fseek(FILE *stream, long offset, int origin): This is the main function. It moves the file pointer to a new position.
stream: The file pointer (e.g., fp).offset: The number of bytes to move (can be positive or negative).origin: The starting point for the offset:
SEEK_SET: Start from the beginning of the file.SEEK_CUR: Start from the current position.SEEK_END: Start from the end of the file (offset is usually negative).ftell(FILE *stream):
long integer.rewind(FILE *stream):
fseek(stream, 0, SEEK_SET);.Example (Reading 5th character, then 2nd from end):
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("data.txt", "w");
fprintf(fp, "0123456789");
fclose(fp);
fp = fopen("data.txt", "r");
if (fp == NULL) return 1;
// Go to the 5th character (index 4)
fseek(fp, 4, SEEK_SET);
printf("5th char is: %c\n", fgetc(fp)); // Output: 4
// Go to the 2nd to last character
fseek(fp, -2, SEEK_END);
printf("2nd to last char is: %c\n", fgetc(fp)); // Output: 8
// Get current position
printf("Current position: %ld\n", ftell(fp)); // Output: 9
// Go back to start
rewind(fp);
printf("First char is: %c\n", fgetc(fp)); // Output: 0
fclose(fp);
return 0;
}
Command-line arguments are parameters passed to a program when it is executed from the terminal. This allows users to provide input or specify options to the program at startup.
In C, these arguments are accessed through the parameters of the main() function:
int main(int argc, char *argv[])
argc (Argument Count): An integer that holds the *number* of arguments passed, including the program's name.argv (Argument Vector): An array of character pointers (an array of strings). Each string is one of the arguments.
argv[0] is always the name of the program itself (e.g., ./a.out).argv[1] is the first actual argument.argv[2] is the second, and so on.argv[argc] is a NULL pointer.Example (Program that prints its arguments):
#include <stdio.h>
// Save as "args.c", compile as "gcc args.c -o myprogram"
// Run as: ./myprogram hello world 123
int main(int argc, char *argv[]) {
int i;
printf("Program name: %s\n", argv[0]);
printf("Number of arguments (argc): %d\n", argc);
if (argc > 1) {
printf("Arguments passed:\n");
for (i = 1; i < argc; i++) {
printf(" argv[%d] = %s\n", i, argv[i]);
}
} else {
printf("No arguments were passed.\n");
}
return 0;
}
Output (when run as ./myprogram hello world 123):
Program name: ./myprogram Number of arguments (argc): 4 Arguments passed: argv[1] = hello argv[2] = world argv[3] = 123
Here is a comparison of sequential and random file access methods:
Sequential Access:
fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf().
// Example: Reading a file sequentially
FILE *fp = fopen("file.txt", "r");
char line[100];
while (fgets(line, 100, fp) != NULL) {
printf("%s", line);
}
fclose(fp);
Random Access:
fseek(), ftell(), rewind() (in combination with fread()/fwrite()).
// Example: Reading the 100th byte
FILE *fp = fopen("data.bin", "rb");
char ch;
fseek(fp, 99, SEEK_SET); // Go to byte 99 (100th byte)
fread(&ch, sizeof(char), 1, fp);
printf("100th byte is: %c\n", ch);
fclose(fp);
Ad Space