cpp File Handling

Published on: 10 February 2025

Resources

  1. Video Lecture

Aim: Create a program to showcase various File Handling operations – open, close, update

Self Assessment

  1. Calculate the moment generated by a force applied at a given distance from a pivot point, and store/retrieve the results using file handling in C++.

Practice Exercise 17: Write a program to demonstrate the concept of torque in mechanical systems using basic file handling operations.

Theory:

Torque is a measure of the rotational force applied to an object, which causes it to rotate about an axis. It is calculated as the product of the force applied and the distance from the pivot point (also known as the moment arm). The formula for torque is given by:

$$ T = F \times d $$

Where: - $ T $ is the torque (measured in Newton-meters, Nm). - $ F $ is the force applied (measured in Newtons, N). - $ d $ is the distance from the pivot point (measured in meters, m).

In mechanical systems, torque is important because it determines the rotational effect of a force, such as when turning a wrench or rotating a wheel.

Algorithm:

  1. Input the force applied to the object ($ F $) and distance from the pivot point ($ d $).

  2. Calculate the torque using the following formula and display the calculated torque value.:

$$ T = F \times d $$

Code:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Create and open the file for writing
    ofstream outFile("torque_calculations.txt");

    // Check if the file is open
    if (!outFile) {
        cerr << "Error opening file for writing." << endl;
        return 1;
    }

    // Torque calculations
    double force = 50.0;  // Force applied in Newtons (N)
    double distance = 2.0; // Distance from pivot in meters (m)
    double torque = force * distance;

    // Write the torque calculation to the file
    outFile << "Force applied: " << force << " N" << endl;
    outFile << "Distance from pivot: " << distance << " m" << endl;
    outFile << "Calculated Torque: " << torque << " Nm" << endl;

    // Close the file after writing
    outFile.close();

    // Open the file for reading
    ifstream inFile("torque_calculations.txt");

    // Check if the file is open
    if (!inFile) {
        cerr << "Error opening file for reading." << endl;
        return 1;
    }

    // Read and display the content of the file
    string line;
    cout << "\nTorque Calculation from the file:\n";
    while (getline(inFile, line)) {
        cout << line << endl;
    }

    // Close the file after reading
    inFile.close();

    return 0;
}

References

There may be some AI Generated content in this article used for demonstration purposes.