Home > Software engineering >  how to store struct in a text file in c
how to store struct in a text file in c

Time:10-21

I want to store the elements of struct into a text file. I have multiple inputs and this is what I have done, however, I can only store the latest inputs but not all the input. Thanks in advance for the help! Here is my code:

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

struct ProcessRecords {
    string ID;
    int arrival;
    int wait;
    int burst;
    
    void putToFile() {
        ofstream input;
        input.open ("process.txt");
        input << ID << "\t" << arrival << "\t" << wait << "\t" << burst << endl;
        input.close();
    }
};

int main() {
    int numProcess;
    int algo;
    
    cout << "\n\t\t=== CPU SCHEDULING ALGORITHMS ===\n";
    cout << "\n\t\tEnter number of processes: ";
    cin >> numProcess;
    ProcessRecords process[numProcess]; 
    string processID[numProcess];
    int arrTime[numProcess];
    int waitTime[numProcess];
    int burstTime[numProcess];
    cout << endl << endl;
    
    for (int i = 0; i < numProcess; i  ) {
        cout << "\n\tEnter process ID for Process " << i 1 << ":\t ";
        cin >> processID[i];
        process[i].ID = processID[i];
        cout << "\n\t\tEnter arrival time for " << processID[i] << ":\t ";
        cin >> arrTime[i];
        process[i].arrival = arrTime[i];
        cout << "\n\t\tEnter waiting time for " << processID[i] << ":\t ";
        cin >> waitTime[i];
        process[i].wait = waitTime[i];
        cout << "\n\t\tEnter burst time for " << processID[i] << ":\t ";
        cin >> burstTime[i];
        process[i].burst = burstTime[i];
        process[i].putToFile();
    }
    
    return 0;
}

Here is my sample output: enter image description here

CodePudding user response:

First In C (by C i mean standard C and not extensions), the size of an array must be a compile time constant. So you cannot write code like:

int n = 10;
int arr[n];    //incorrect

Correct way to write this would be:

const int n = 10;
int arr[n];    //correct

For the same reason the following statement is incorrect in your code :

int arrTime[numProcess]; //incorrect because size of array must be fixed and decide at compile time 

Second you should append to the text file instead of overwriting it. For opening the file in append mode you can use:

input.open("process.txt", ofstream::app);

You can check here that the program works(append) as you desire, using input.open("process.txt", ofstream::app); . Also do note what i said about the size of array being compile time constant. I have not changed it in the link i have given. You can use std::vector for variable size container.

  • Related