Tuesday, 3 December 2024

OOPS C++ File Operations MSBTE III Sem

Unit 5

Q1. What is sequential access? Describe with diagram.

Ans. Sequential access is a method of accessing data in a specific order, from the beginning to the end, one record at a time. This method is commonly used for processing files, such as text files or binary files, where data is read or written sequentially.

Characteristics of Sequential Access:

1.     Data is processed in the order it is stored.

2.     Suitable for scenarios where data needs to be read linearly (e.g., logs, configuration files).

3.     Slower for random access, as accessing a specific record requires iterating through all preceding records.

 

Q2. What is random access? Explain with suitable diagram.

Ans. Random access refers to the ability to access data at any position in a file or dataset directly, without reading through preceding data. Unlike sequential access, which requires processing data in order, random access allows jumping to a specific location and retrieving or modifying data efficiently.

Characteristics of Random Access:

1.     Direct access to any part of the file or dataset.

2.     Faster for accessing specific records compared to sequential access.

3.     Useful for applications like database systems, index-based file processing, or large binary files.

C++ provides functions for random access to files using the seekg (for input) and seekp (for output) methods of file streams. These functions reposition the file pointer to a specific byte offset.

 

Q3. Compare sequential and random access.

Comparison of Sequential Access and Random Access in C++

Aspect

Sequential Access

Random Access

Definition

Data is accessed sequentially, one record at a time, in order.

Data can be accessed directly at any position in the file.

Access Speed

Slower for accessing specific records as it processes from the start.

Faster for accessing specific records due to direct positioning.

File Pointer Movement

Moves automatically to the next record after each operation.

Explicitly moved to a specific position using seekg or seekp.

Flexibility

Limited to linear data processing.

More flexible, allowing jumps to any part of the file.

Ease of Use

Easier to implement and understand.

Requires additional logic for managing file pointers.

Use Cases

Suitable for reading logs, processing sequential data.

Ideal for databases, large files, and index-based access.

File Stream Methods

getline, read, and automatic pointer progression.

seekg, seekp for moving pointers, and read or write.

 

Summer 2022

Q4. Explain los:app and losin flags. (2 Marks)

Ans.

ios::app (Append Mode):

  • Opens a file in append mode.
  • All data written to the file is added at the end, preserving the existing content.
  • Used with ofstream or fstream for writing.

Example:

ofstream file("example.txt", ios::app);

file << "Appended data.\n";

file.close();

ios::in (Input Mode):

  • Opens a file for reading.
  • Used with ifstream or fstream to read data sequentially.
  • File must exist; otherwise, opening will fail.

Example:

ifstream file("example.txt", ios::in);

string line;

while (getline(file, line)) {

    cout << line << endl;

}

file.close();

 

Q5. List C++ stream classes along with their function (any two classes). (2 Marks)

Ans.

  ifstream (Input File Stream):

  • Used for reading data from files.
  • Functions:
    • open(): Opens a file for reading.
    • getline(): Reads a line of text from the file.
    • eof(): Checks if the end of the file is reached.

Example:

ifstream file("example.txt");

string line;

while (getline(file, line)) {

    cout << line << endl;

}

file.close();

  ofstream (Output File Stream):

  • Used for writing data to files.
  • Functions:
    • open(): Opens a file for writing.
    • <<: Inserts data into the file.
    • close(): Closes the file.

Example:

ofstream file("output.txt");

file << "Writing to a file.\n";

file.close();


Q6. Write a C program to copy the contents of a source file
student.txt to a destination file student2.txt using file operation.

Ans.

Here is a C program to copy the contents of a file student1.txt to another file student2.txt using file

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    FILE *sourceFile, *destFile;

    char sourceFileName[] = "student1.txt";

    char destFileName[] = "student2.txt";

    char ch;

 

    // Open the source file in read mode

    sourceFile = fopen(sourceFileName, "r");

    if (sourceFile == NULL) {

        printf("Error: Could not open source file %s\n", sourceFileName);

        exit(1);

    }

 

    // Open the destination file in write mode

    destFile = fopen(destFileName, "w");

    if (destFile == NULL) {

        printf("Error: Could not open destination file %s\n", destFileName);

        fclose(sourceFile);

        exit(1);

    }

 

    // Copy contents from source to destination

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

        fputc(ch, destFile);

    }

 

    printf("File copied successfully from %s to %s.\n", sourceFileName, destFileName);

 

    // Close the files

    fclose(sourceFile);

    fclose(destFile);

 

    return 0;

}

Explanation

1.     Opening Files:

o   The fopen function opens student1.txt in read mode ("r") and student2.txt in write mode ("w").

2.     Error Checking:

o   If either file fails to open, an error message is displayed, and the program exits.

3.     Copying Contents:

o   The program reads characters from the source file using fgetc and writes them to the destination file using fputc.

4.     Closing Files:

o   Both files are closed using fclose to release resources.

Output Example:

Content of student1.txt:

Hello, World!

This is a test file.

 

Winter 2022

Q7. Explain file modes used to perform file operations. (2 Marks)

Ans.

File modes in C++ determine how files are opened for reading or writing. These modes are defined in the <fstream> library and can be combined using the | operator.

1.     ios::in: Opens a file for reading.

o   Example: fstream file("example.txt", ios::in);

2.     ios::out: Opens a file for writing.

o   If the file exists, its content is erased (truncated).

o   Example: ofstream file("example.txt", ios::out);

3.     ios::app: Opens a file for appending data.

o   Data is always written at the end of the file.

o   Example: fstream file("example.txt", ios::app);

4.     ios::binary: Opens a file in binary mode.

o   Used for non-text data.

o   Example: fstream file("example.bin", ios::binary);

These modes help control how data is read from or written to files.

Q8. List all stream classes used in stream operation. (2 Marks)

Ans. The following are the stream classes used for file and console input/output in C++:

1.     istream:

o   Handles input operations.

o   Example: cin for console input.

2.     ostream:

o   Handles output operations.

o   Example: cout for console output.

3.     ifstream:

o   Handles input (reading) from files.

4.     ofstream:

o   Handles output (writing) to files.

5.     fstream:

o   Handles both input and output operations on files.

These classes are part of the <iostream> and <fstream> libraries and provide flexible mechanisms for data handling.

Q9 . Develop C++ program to open and read content of file also write "object oriented" string in file and close it

Ans.

#include <iostream>

#include <fstream>

using namespace std;

 

int main() {

    // Create an output file stream object

    ofstream fout;

   

    // Open the file "abc.txt" in write mode

    fout.open("abc.txt", ios::out);

   

    // Write to the file

    fout << "Object Oriented";

   

    // Close the file after writing

    fout.close();

   

    // Create an input file stream object

    ifstream fin;

    char line[100];

   

    // Open the file "abc.txt" in read mode

    fin.open("abc.txt", ios::in);

   

    // Check if the file was opened successfully

    if (!fin) {

        cout << "Error opening file." << endl;

        return 1; // Exit the program if file couldn't be opened

    }

 

    cout << "Contents of the file are:\n";

   

    // Read the file line by line

    while (fin.getline(line, 100)) {

        cout << line << "\n";  // Print each line to the console

    }

 

    // Close the file after reading

    fin.close();

   

    return 0;

}

Output

Contents of the file are:

Object Oriented

Q10. Develop C++ program to check Detection of end of file. (4 Marks)

Ans.

Here is a C++ program to detect the end of the file (EOF) while reading data from a file. This program will read the contents of a file and stop when it reaches the end of the file.

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ifstream file("example.txt");  // Open file in read mode

    string line;

 

    // Check if the file opened successfully

    if (!file) {

        cout << "Error opening file." << endl;

        return 1;  // Exit if the file cannot be opened

    }

    cout << "Contents of the file are:" << endl;

    // Read the file line by line until EOF

    while (getline(file, line))

{

        cout << line << endl;  // Print the line to console

    }

 

    // After the loop, we know EOF has been reached

    if (file.eof()) {

        cout << "\nEnd of file reached." << endl;

    }

    file.close();  // Close the file

    return 0;

}

Key Points:

  • The program reads the file line by line using getline(), which simplifies the process of handling the end of the file (EOF).
  • The program uses file.eof() to explicitly confirm that EOF has been reached.

Summer 2023

Q11. Define file with its operations. (2 Marks)

Ans. A file in C++ is a collection of data stored in a permanent storage medium (like a hard drive). C++ provides input/output stream classes to perform operations on files.

File Operations in C++:

1.     Opening a File:

o   Use ifstream for reading, ofstream for writing, and fstream for both.

o   Example: ifstream file("file.txt");

2.     Reading from a File:

o   Use functions like getline(), get(), or stream extraction (>>).

o   Example: getline(file, line);

3.     Writing to a File:

o   Use stream insertion (<<) or write().

o   Example: file << "Hello, World!";

4.     Closing a File:

o   Always close the file after performing operations using close().

o   Example: file.close();

These operations allow you to manage file input and output effectively in C++.

Q12. Write a program for get and put functions (4 Marks)

Ans.

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    // Create an output file stream object to write data to a file

    ofstream fout("example.txt");

    // Check if the file is open for writing

    if (!fout) {

        cout << "Error opening file for writing." << endl;

        return 1;  // Exit if file can't be opened

    }

    // Writing individual characters using put() to the file

    fout.put('H');

    fout.put('e');

    fout.put('l');

    fout.put('l');

    fout.put('o');

    fout.put(' ');

    fout.put('W');

    fout.put('o');

    fout.put('r');

    fout.put('l');

    fout.put('d');

    fout.put('!');

    fout.put('\n');  // Adding a newline character at the end

    // Close the file after writing

    fout.close();

    // Create an input file stream object to read data from the file

    ifstream fin("example.txt");

    // Check if the file is open for reading

    if (!fin) {

        cout << "Error opening file for reading." << endl;

        return 1;  // Exit if file can't be opened

    }

    // Declare a variable to hold the character read from the file

    char ch;

    // Reading individual characters using get() from the file

    cout << "Contents of the file are: ";

    while (fin.get(ch)) {  // While we are reading characters until EOF

        cout.put(ch);  // Display the character read from the file

    }

    cout << endl;

    // Close the file after reading

    fin.close();

 

    return 0;

}

Explanation:

1.     Writing to the File Using put():

o   The program opens a file named example.txt in output mode using ofstream.

o   The put() function is used to write individual characters ('H', 'e', 'l', etc.) to the file one by one.

o   A newline character ('\n') is added at the end of the string.

o   After writing, the file is closed using fout.close().

2.     Reading from the File Using get():

o   The program then opens the same file example.txt in input mode using ifstream.

o   It reads one character at a time from the file using get(), which stores each character in the variable ch.

o   The cout.put(ch) function is used to display the character on the console.

o   The loop continues until the end of the file (EOF) is reached.

3.     File Operations:

o   The file is properly opened and closed, and error checking is done to ensure that the file is accessible for both reading and writing.

o   get() and put() are low-level functions that work with individual characters, giving you control over character-based file operations.

Expected Output:

If the file example.txt contains the text "Hello World!", the output displayed on the console will be:

sql

Contents of the file are: Hello World!

Key Concepts:

  • get(): Reads a single character from the input stream.
  • put(): Writes a single character to the output stream.
  • File Handling: The program demonstrates basic file handling, including opening, reading, writing, and closing files.

 

Q13. Write a program for closing a file. (4 Marks)

Ans.

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    // Create an output file stream object to write data to a file

    ofstream fout("output.txt");

    // Check if the file is open for writing

    if (!fout) {

        cout << "Error opening output file for writing." << endl;

        return 1;  // Exit if the file can't be opened

    }

    // Writing some data to the file

    fout << "This is a test file." << endl;

    fout << "C++ file operations are fun!" << endl;

    // Close the output file after writing

    fout.close();

    cout << "File 'output.txt' has been written and closed." << endl;

    // Create an input file stream object to read data from the file

    ifstream fin("output.txt");

    // Check if the file is open for reading

    if (!fin) {

        cout << "Error opening output file for reading." << endl;

        return 1;  // Exit if the file can't be opened

    }

    // Reading and displaying the contents of the file

    string line;

    cout << "Contents of the file 'output.txt':" << endl;

    while (getline(fin, line)) {

        cout << line << endl;  // Display each line from the file

    }

    // Close the input file after reading

    fin.close();

    cout << "File 'output.txt' has been read and closed." << endl;

    return 0;

}

Output

File 'output.txt' has been written and closed.

Contents of the file 'output.txt':

This is a test file.

C++ file operations are fun!

File 'output.txt' has been read and closed.

 

Winter 2023

Q14 . Give the syntax and use of fclose() function

Ans. The syntax of the fclose() function is,

int fclose(FILE "stream).

The fclose() function in C is used to close an open file. When a file is opened using functions like fopen(), fclose() should be called to close the file and release any resources associated with it.

Syntax:

int fclose(FILE *stream);

  • stream: A pointer to the FILE object that represents the file to be closed. This pointer is returned by functions like fopen().

Return Value:

  • If the file is successfully closed, fclose() returns 0.
  • If an error occurs while closing the file, it returns EOF.

Q15. Write a C program to copy data from one file to another.

Ans. #include <iostream>

#include <fstream>

#include <cstring>

using namespace std;

 

int main() {

    // File names

    string sourceFile = "source.txt";

    string destFile = "destination.txt";

 

    // Open the source file in read mode

    ifstream src(sourceFile, ios::binary);

    if (!src) {

        cerr << "Error opening source file!" << endl;

        return 1;

    }

 

    // Open the destination file in write mode

    ofstream dest(destFile, ios::binary);

    if (!dest) {

        cerr << "Error opening destination file!" << endl;

        return 1;

    }

 

    // Copy the content from source to destination

    dest << src.rdbuf();

 

    cout << "Data copied successfully from " << sourceFile << " to " << destFile << endl;

 

    // Close the files

    src.close();

    dest.close();

 

    return 0;

}

 

Summer 2024

Q16. List C++ stream classes along with their function any two classes (2 Marks)

Ans.

1. ifstream (Input File Stream):

  • Purpose: Used to read data from files.
  • Functions:
    • open(): Opens the file for reading.
    • close(): Closes the file.
    • getline(): Reads a line of text from the file.
    • operator>>: Extracts data from the file.

2. ofstream (Output File Stream):

  • Purpose: Used to write data to files.
  • Functions:
    • open(): Opens the file for writing.
    • close(): Closes the file.
    • operator<<: Writes data to the file.
    • flush(): Forces the buffer to be written to the file immediately.

These are the basic functions provided by the ifstream and ofstream classes for reading and writing files in C++.

Q17. Write a program to count number of lines in a file

Ans.

#include <iostream>

#include <fstream>

using namespace std;

 

int main() {

    int count = 0;  // Initialize count to 0

    string line;    // Declare a string to store each line

 

    ifstream file("abc.txt");  // Open the file "abc.txt"

 

    if (!file) {  // Check if the file opened successfully

        cerr << "Unable to open the file!" << endl;

        return 1;  // Exit if file cannot be opened

    }

 

    // Count the number of lines in the file

    while (getline(file, line)) {

        count++;  // Increment count for each line

    }

 

    cout << "Number of lines in the file: " << count << endl;

 

    file.close();  // Close the file

    return 0;

}


Q18. Develop a C++ program to read content of file abc.txt

Ans.

#include <iostream>

#include <fstream>

using namespace std;

 

int main() {

    // Open the file "abc.txt" in input mode

    fstream inputFile("abc.txt", ios::in);

 

    // Check if the file was opened successfully

    if (inputFile.is_open()) {

        string line;  // Declare a string to hold each line

 

        // Read the file line by line

        while (getline(inputFile, line)) {

            cout << line << endl;  // Output each line

        }

 

        // Close the file after reading

        inputFile.close();

    } else {

        cerr << "Unable to open the file!" << endl;  // If the file couldn't be opened

    }

 

    return 0;

}

 


No comments:

Post a Comment

Summer 2018 Programming in C Solved Question Paper

Summer 2018 Semester II – C Programming   Q1. Attempt any FIVE of the following : 10 (a) Define : (i) Two dimensional array In C...