0% found this document useful (0 votes)
3 views

problem solving using c full course paart 4

The document provides a comprehensive overview of file handling in C, covering the definition of files, types of files (text and binary), file streams, operating modes, and various file processing functions. It includes examples of standard I/O functions, formatted I/O functions, file positioning functions, character I/O functions, binary I/O functions, and command line arguments. Additionally, it presents several C programs demonstrating practical file operations such as counting characters, copying content, and reversing characters in a file.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

problem solving using c full course paart 4

The document provides a comprehensive overview of file handling in C, covering the definition of files, types of files (text and binary), file streams, operating modes, and various file processing functions. It includes examples of standard I/O functions, formatted I/O functions, file positioning functions, character I/O functions, binary I/O functions, and command line arguments. Additionally, it presents several C programs demonstrating practical file operations such as counting characters, copying content, and reversing characters in a file.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1. What is a File?

A file is a collection of data that is stored on a storage medium such as a hard disk, solid-state drive
(SSD), USB flash drive, or other storage devices. Files are used to store various kinds of data, such
as text, images, videos, and application data. Files are typically organized by their names and
extensions (e.g., .txt, .bin, .exe). A file can be opened, read, written, or modified by a
computer program or operating system. In C, files are represented as pointers to the FILE structure.

Files are of two main types:


1. Text Files: These contain data that is human-readable (e.g., source code, log files).
2. Binary Files: These store data in binary form, making it unreadable to humans (e.g., images,
compiled program files).

2. What are the Different File Streams?


In C, file handling is done using streams, which abstract the process of reading from and writing to
files. There are three standard file streams in C:
1. Standard Input (stdin): This stream is used for reading input. By default, stdin reads
from the keyboard, but it can also be redirected to read from a file or other devices.
2. Standard Output (stdout): This stream is used to output data to the screen. By default,
stdout sends output to the console, but it can also be redirected to a file or other devices.
3. Standard Error (stderr): This stream is used to output error messages. Like stdout,
stderr usually sends output to the screen but is used specifically for error reporting. It can
also be redirected to a file.

3. What is the Difference Between Text Files and Binary Files?


There are two primary types of files based on the format in which data is stored:
1. Text Files:
• These store data as a sequence of readable characters (ASCII or Unicode).
• Each line in a text file ends with a newline character (\n), and the data is stored as
plain text.
• Text files are human-readable and can be opened and edited with text editors like
Notepad, Sublime Text, etc.
• Examples: .txt, .csv, .html.
• Text files are also called character files.
2. Binary Files:
• Binary files store data in binary format, which means they contain sequences of bytes
that represent data, which is typically not human-readable.
• Binary files are used to store complex data structures, like images, audio files, video
files, or compiled programs.
• Unlike text files, they do not contain newline characters, and data is stored in the
form of binary representations.
• Examples: .exe, .jpg, .pdf.
• Binary files are not human-readable but are efficient for storing large amounts of
data in their original format.

4. What are the Different File Operating Modes?


When opening a file in C, you must specify the file operating mode. These modes dictate how the
file is accessed. The most common file operating modes are:
1. r (Read): Opens an existing file for reading. If the file does not exist, the program will
return an error.
2. w (Write): Opens a file for writing. If the file exists, its content will be truncated to zero
length. If the file doesn't exist, it will be created.
3. a (Append): Opens a file for appending. If the file doesn't exist, it is created. Data will be
added at the end of the file.
4. r+ (Read and Write): Opens an existing file for both reading and writing. The file must
exist; otherwise, an error occurs.
5. w+ (Write and Read): Opens a file for both reading and writing. If the file exists, it will be
truncated; if it does not exist, it will be created.
6. a+ (Append and Read): Opens a file for both reading and appending. The file is created if
it doesn't exist, and the file pointer is placed at the end of the file.

5. What are the Various File Stream File Processing?


In C, file processing is the handling of files using streams. The basic steps involved in file stream
processing are:
1. Opening a File: A file is opened using the fopen() function. It requires two arguments:
the file name and the file mode (e.g., r, w, etc.). Example:
c
Copy code
FILE *file = fopen("example.txt", "r");

2. Reading from a File: Files can be read character by character or in blocks. Common
functions for reading include:
• fgetc() – Reads a single character from a file.
• fgets() – Reads a line from the file.
• fread() – Reads a block of data.
3. Writing to a File: Data can be written using the following functions:
• fputc() – Writes a single character to a file.
• fputs() – Writes a string to a file.
• fwrite() – Writes a block of data to a file.
4. Closing a File: Once the operations on a file are completed, the file should be closed using
the fclose() function to release resources. Example:
c
Copy code
fclose(file);

6. What are the Standard I/O Functions with an Example?


Standard I/O functions in C provide basic input and output functionality to interact with the user or
system:
• printf(): Outputs formatted data to the console.
• scanf(): Reads input from the user.
• getchar(): Reads a single character from the standard input (keyboard).
• putchar(): Outputs a single character to the standard output (console).

Example:
c
Copy code
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number); // Reads an integer from the user
printf("You entered: %d\n", number); // Prints the entered number
return 0;
}

7. What are the Formatted I/O Functions with an Example?


Formatted I/O functions allow the user to read and write data with specific formatting:
• printf(): Outputs data with a specific format.
• scanf(): Reads data with a specific format. These functions provide control over how
data is presented (e.g., number of decimal places, padding, alignment).
Example (formatted output with printf):
c
Copy code
#include <stdio.h>
int main() {
float pi = 3.14159;
printf("Pi value with two decimal points: %.2f\n", pi); // formatted output
return 0;
}

This will output: Pi value with two decimal points: 3.14.

8. What are the File Positioning Functions with an Example?


File positioning functions are used to manipulate the file pointer’s position within a file:
1. ftell(): Returns the current file pointer position. Example:
c
Copy code
long pos = ftell(file);
printf("Current position: %ld\n", pos);

2. fseek(): Moves the file pointer to a specified location. Example:


c
Copy code
fseek(file, 5, SEEK_SET); // Moves the pointer to the 5th byte

3. rewind(): Resets the file pointer to the beginning of the file. Example:
c
Copy code
rewind(file); // Moves the pointer to the start of the file

9. What are the Character I/O Functions with an Example?


Character I/O functions work with characters, reading and writing them one at a time:
• fgetc(): Reads one character from a file.
• fputc(): Writes one character to a file.
• getchar(): Reads a character from the standard input.
• putchar(): Writes a character to the standard output.

Example:
c
Copy code
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file) {
fputc('A', file); // Writes a character 'A' to the file
fclose(file);
}
return 0;
}

10. What are the Binary I/O Functions with an Example?


Binary I/O functions handle data in binary format:
• fread(): Reads binary data from a file.
• fwrite(): Writes binary data to a file.

Example (writing and reading a binary file):


c
Copy code
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
FILE *file = fopen("binary.dat", "wb");
fwrite(arr, sizeof(int), 3, file); // Writing binary data
fclose(file);

FILE *readFile = fopen("binary.dat", "rb");


fread(arr, sizeof(int), 3, readFile); // Reading binary data
fclose(readFile);

for (int i = 0; i < 3; i++) {


printf("%d ", arr[i]);
}
return 0;
}

11. Explain About Command Line Arguments with an Example?


Command line arguments are passed to a program when it is executed via the command line. They
provide a way for users to input parameters into the program during execution.
• argc: Argument count (the number of arguments passed to the program, including the
program name).
• argv[]: Array of strings (the actual arguments passed to the program).

Example:
c
Copy code
#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;
}

12. Write a C Program to Display the Count of Characters, Words, and Lines in a File
c
Copy code
#include <stdio.h>
#include <ctype.h>

int main() {
FILE *file = fopen("example.txt", "r");
if (!file) {
printf("File not found!\n");
return 1;
}

int ch, charCount = 0, wordCount = 0, lineCount = 0;


int inWord = 0;

while ((ch = fgetc(file)) != EOF) {


charCount++;

if (ch == '\n') lineCount++;


if (isspace(ch)) {
if (inWord) {
wordCount++;
inWord = 0;
}
} else {
inWord = 1;
}
}
if (inWord) wordCount++; // for the last word
printf("Characters: %d\nWords: %d\nLines: %d\n", charCount, wordCount,
lineCount);
fclose(file);
return 0;
}

13. Write a C Program to Read Content of One File and Display


c
Copy code
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (!file) {
printf("File not found!\n");
return 1;
}

char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Display the content
}
fclose(file);
return 0;
}

14. Write a C Program to Copy Content of One File to Another File


c
Copy code
#include <stdio.h>
int main() {
FILE *source = fopen("source.txt", "r");
FILE *destination = fopen("destination.txt", "w");

if (!source || !destination) {
printf("File error!\n");
return 1;
}

char ch;
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination); // Copy character by character
}
fclose(source);
fclose(destination);
return 0;
}
15. Write a C Program to Append One File to Another File
c
Copy code
#include <stdio.h>
int main() {
FILE *source = fopen("source.txt", "r");
FILE *destination = fopen("destination.txt", "a");

if (!source || !destination) {
printf("File error!\n");
return 1;
}

char ch;
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination); // Append content to the destination
}
fclose(source);
fclose(destination);
return 0;
}

16. Write a C Program to Reverse the First N Characters of a File


c
Copy code
#include <stdio.h>
#include <string.h>
#define MAX 100

void reverse(char *str, int n) {


int start = 0, end = n - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}

int main() {
FILE *file = fopen("example.txt", "r+");
if (!file) {
printf("File not found!\n");
return 1;
}

char buffer[MAX];
int n = 5; // Number of characters to reverse
fread(buffer, sizeof(char), n, file);
reverse(buffer, n);
fseek(file, 0, SEEK_SET); // Move pointer back to the start
fwrite(buffer, sizeof(char), n, file);
fclose(file);
return 0;
}

You might also like