Why won't my ofstream make a new file with the context??? It only makes a blank file?

My input file is "widgets.dat", how do i close the program when done & rename/re-create a new file as prog2.out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  
struct Item {
	int partNumber;    // number of the part
	string partName;   // description of part
	int partQuantity;  // quantity remaining
	double price;      // price of the part

	Item(int p, const string& pnam, int q, double pr) : partNumber(p), partName(pnam), partQuantity(q), price(pr) {}
};

bool openFileIn(fstream&, const string&);        // used to open file
vector<Item> getItems(fstream&);                 // retrieves the items
void showItems(const vector<Item>&);             // displays the items
vector<string> split(const string&, char = ','); // split strings into sub-strings

int main()
{
	fstream dataFile;       // data file

	if (openFileIn(dataFile, "widgets.dat"))
	{
		const auto items {getItems(dataFile)};

		dataFile.close();
		showItems(items);

		// save file to new file




Last edited on
I'm getting a whole bunch of errors just trying to even use those declarations from that link
Can someone show me how to do this i'm still not understanding
You have several options:

(1) Given the data contained in your items vector, write that information to a new filename.
(2) Read in widgets.dat (ifstream), and then dump it into another ofstream.
(3) <cstdio>'s rename function: http://www.cplusplus.com/reference/cstdio/rename/
(4) <filesystem>'s rename function (jonnin already linked it)
(5) Some OS-specific API.

Example of #2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>

int main()
{
	std::ifstream fin("existing_file.txt");
	std::ofstream fout("new_file.txt");
	
	if (!fin)
	{
		std::cout << "Error: Could not open existing file for reading.\n";
		return 1;
	}
	if (!fout)
	{
		std::cout << "Error: Could not open new file for writing.\n";
		return 1;
	}
	
	fout << fin.rdbuf(); // dump contents from fin to fout.
	return 0;
}
Last edited on
I understand your second example but i'm not allowed to use std::cout, so i did it another way.... my way creates the file i need but doesn't include the context, please help with this minor problem this is due tomorrow and i've been so stuck on this . WHY DOESN'T MY LINE 80-81 DISPLAY MY CONSOLE NUMBERS/OUTPUT IN MY OUTPUT FILE??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

struct Item {
	int partNumber;
	string partName;
	int partQuantity;
	double price;

	Item(int p, const string& pnam, int q, double pr) : partNumber(p), partName(pnam), partQuantity(q), price(pr) {}
};

bool openFileIn(fstream&, const string&);
vector<Item> getItems(fstream&);
void showItems(const vector<Item>&);
vector<string> split(const string&, char = ',');

int main()
{
	fstream dataFile;       // data file

	if (openFileIn(dataFile, "widgets.dat"))
	{
		const auto items {getItems(dataFile)};

		dataFile.close();
		showItems(items);

		openFileIn(dataFile, "prog2.out");
	} else
		cout << "File open error!" << endl;
}

//***********************************************************
// Definition of function openFileIn. Accepts a reference   *
// to an fstream object as an argument. The file is opened  *
// for input. The function returns true upon success, false *
// upon failure.                                            *
//***********************************************************

bool openFileIn(fstream& file, const string& name)
{
	file.open(name.c_str(), ios::in);
	return file.is_open();
}

/*
 * getStudent data one line at a time from
 * the file. Parse the line using ',' as delimiter.
 * Save data read to an Item, recorded in 'vs'.
 */
vector<Item> getItems(fstream& file)
{
	vector<Item> vs;
	string input;

	//Remove header line
	getline(file, input);

	// Read item data from file using ',' as a delimiter.
	while (getline(file, input)) {
		const auto tokens {split(input)};
		const auto& nam {tokens.at(1)};
		vs.emplace_back(atoi(tokens.at(0).c_str()), nam.substr(2, nam.size() - 3), atoi(tokens.at(2).c_str()), atof(tokens.at(3).c_str()));
	}

	return vs;
}

/*
 * show all items
 */
void showItems(const vector<Item>& vs)
{
        ofstream outputFile;
        outputFile.open("prog2.out.");

	/* Display the headings for each column, with spacing and justification flags */
	printf("%-12s%-25s%-20s%-8s\n", "Part Number", "Description", "Quantity in Stock", "Price");

	// Read item data from file using ',' as a delimiter.
	for (const auto& item : vs) {
		if (item.partNumber != 0) {
			printf("%-12d%-30s%-15d%-2.2f\n",
				item.partNumber,
				item.partName.c_str(),
				item.partQuantity,
				item.price
			);
		}

		/* If the id field is zero, then we reached the last, break out of the for loop. */
		else
			break;
			outputFile.close();

	}



}

//**************************************************************
// The split function splits s into tokens, using delim as the *
// delimiter. The tokens are added to the tokens vector.       *
//**************************************************************
vector<string> split(const string& s, char delim)
{
	vector<string> tokens;

	int tokenStart = 0, delimPosition = s.find(delim);

	// While string is not at end:
	while (delimPosition != string::npos)
	{

		// Push the token onto the tokens vector.
		tokens.push_back(s.substr(tokenStart, delimPosition - tokenStart));

		// Move delimPosition to the next character position.
		delimPosition++;

		// Move tokenStart to delmiPosition.
		tokenStart = delimPosition;

		// Get next delimPosition.
		delimPosition = s.find(delim, tokenStart);
	}
	tokens.push_back(s.substr(tokenStart, string::npos));

	return tokens;
}
Last edited on
Line 81 opens a file called "prog2.out." (for writing).

Are you saying you want the printf functions to be writing to your file? printf just prints to standard out. It doesn't write to your file. (You can do file redirection, but I assume that's outside the scope of this assignment.)

I think the easiest modification here would to use sprintf instead of printf.

1
2
3
4
5
6
7
	char buffer[1000] {};
	sprintf(buffer, "%-12d%-30s%-15d%-2.2f\n", 
			item.partNumber,
			item.partName.c_str(),
			item.partQuantity,
			item.price);
	outputFile << buffer;
Last edited on
I want my program to open up widgets.dat using fstream, and then create a new file called prog2.out

I basically open that with fstream, program organizes that nicely, then saves it to a new file called prog2.out

Part Number, Description, Quantity in Stock, Price
23093, "Basic Widget", 143, 299.99
23355, "Mid-Range Widget", 2556, 749.99
21546, "Advanced Widget", 14, 1599.99
25483, "Special Order Widget", 0, 3100.00
Last edited on
I tried using that char buffer idea, but it erases all my contexts and only keeps the headers when i run the program
Last edited on
Post the code where you think the problem is. Maybe someone will be able to take a look at it before tomorrow.

You can also just mess around with doing something like:
outputFile << item.partNumber << ", " << item.partName << ", " << item.partyQuantity << ", " << item.price << '\n';
Last edited on
Ugh idk where the problem is my professor said all we had to do was write ofstream in our showItems function, and i did that, yet u told me i only began writing to it, i don't get how inserting that doesn't include my program output into the new file. i've been reading my book and countless websites for hours, so like idek what else to try.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void showItems(const vector<Item>& vs)
{
        char buffer[1000] {};
        ofstream outputFile("prog2.out");

	/* Display the headings for each column, with spacing and justification flags */
        sprintf(buffer, "%-12s%-25s%-20s%-8s\n", "Part Number", "Description", "Quantity in Stock", "Price");
        outputFile << buffer;
        printf("%s", buffer);

	// Read item data from file using ',' as a delimiter.
	for (const auto& item : vs) {
		if (item.partNumber != 0) {
			sprintf(buffer, "%-12d%-30s%-15d%-2.2f\n",
				item.partNumber,
				item.partName.c_str(),
				item.partQuantity,
				item.price
			);
                        outputfile << buffer;
                        printf("%s", buffer);
		}

		/* If the id field is zero, then we reached the last, break out of the for loop. */
		else
			break;
			outputFile.close();

	}



}

Ahh i guess that was it, what kinda modification does it need to print everything to the file tho...? It only prints the header, and the first horizontal column. You are truly a blessing seeplus



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

void showItems(const vector<Item>& vs)
{
        char buffer[1000] {};
        ofstream outputFile("prog2.out");

	/* Display the headings for each column, with spacing and justification flags */
        sprintf(buffer, "%-12s%-25s%-20s%-8s\n", "Part Number", "Description", "Quantity in Stock", "Price");
        outputFile << buffer;
        printf("%s", buffer);

	// Read item data from file using ',' as a delimiter.
	for (const auto& item : vs) {
		if (item.partNumber != 0) {
			sprintf(buffer, "%-12d%-30s%-15d%-2.2f\n",
				item.partNumber,
				item.partName.c_str(),
				item.partQuantity,
				item.price
			);
                        outputfile << buffer;
                        printf("%s", buffer);
		}

		/* If the id field is zero, then we reached the last, break out of the for loop. */
		else
			break;
			outputFile.close();

	}



}
line 28 `outputFile.close();' is not inside the else

> but doesn't include the context
¿what do you understand by context?
¿did you mean content?


perhaps you should start writing your own code instead of copy-paste other solutions
It only prints the header, and the first horizontal column


Doh! The outputFile.close() is in the wrong place. I didn't test it..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void showItems(const vector<Item>& vs)
{
	char buffer[1000] {};
	ofstream outputFile("prog2.out");

	/* Display the headings for each column, with spacing and justification flags */
	sprintf(buffer, "%-12s%-25s%-20s%-8s\n", "Part Number", "Description", "Quantity in Stock", "Price");
	outputFile << buffer;
	printf(buffer);

	// Read item data from file using ',' as a delimiter.
	for (const auto& item : vs) {
		if (item.partNumber != 0) {
			sprintf(buffer, "%-12d%-30s%-15d%-2.2f\n",
				item.partNumber,
				item.partName.c_str(),
				item.partQuantity,
				item.price
			);
			outputFile << buffer;
			printf(buffer);
		}

		/* If the id field is zero, then we reached the last, break out of the for loop. */
		else
			break;
	}
	outputFile.close();
}


Well when i sit here for hours and can't figure it out, getting the answer and reviewing it is better so i can continue learning, i've worked on this simple program for like 15+ hours, i'm not very good and my classes are hard since it's remote. Also i tried putting outputFile.close(); there and few other places, still doesn't work


line 28 `outputFile.close();' is not inside the else

> but doesn't include the context
¿what do you understand by context?
¿did you mean content?


perhaps you should start writing your own code instead of copy-paste other solutions
The problem isn't how long you've been trying to do something. The problem is that you're not successfully communicating what the actual issue is to us. (Edit: We all posted at roughly the same time, see seeplus's latest post)
Last edited on
Oh okay my bad, so the issue is i can't get everything to display into the output file... this is my result even with the recent suggestions:

Part Number Description Quantity in Stock Price
23093 Basic Widget 143 299.99




The problem isn't how long you've been trying to do something. The problem is that you're not successfully communicating what the actual issue is to us. (Edit: We all posted at roughly the same time, see seeplus's latest post)

I actually just fixed the issue!
Thanks for the support, you guys are freakin awesome! Have an amazing rest of your weeks... actually lives, my mood just skyrocketed by finally finishing this
Topic archived. No new replies allowed.