Where is the file?

WARNING : The problem stated here is extremely noobish!

I have created a blank CPP project in visual studio. It should create a file named pt_data.bin at D:\ but the file is found nowhere. Even when I remove the path, its not in the project folder.

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
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

class element
{
public:
	char name[20],sym[5];
	int Z, A;
	float atwt;
	element()
	{
		cout << "Enter the details of elements as directed : \nName : ";
		cin.getline(name, 20);
		cout << "Symbol : ";
		cin.getline(sym, 5);
		cout << "Atomic no : ";
		cin >> Z;
		cout << "Mass no : ";
		cin >> A;
		cout << "Aomic wt : ";
		cin >> atwt;
	}
	void elementinput(int z, int a, float awt, char nm[20],char sm[5])
	{
		strcpy_s(name,nm);
		strcpy_s(sym, sm);
		Z=z;
		A=a;
		atwt=awt;
	}
};

int main()
{
	element e1;
	fstream fout("D:\\pt_data.bin", ios::binary);
	fout.write((char*)&e1,sizeof(e1));
	system("pause");
	fout.close();
	return 0;
}


An fstream will not create a file if it doesn't exist when using the default open modes. If you want to create the file if it doesn't exist you will need to use the ios::app mode when opening the file.

You should always check if you successfully open the file before trying to do anything with the file.

1
2
3
4
5
6
7
8
...
   fstream fout("D:\\pt_data.bin", ios::app |  ios::binary);
   if(!fout)
   {
      cerr << "Couldn't open the file for writing." ;
      return 1;
   }
   ...
Last edited on
The default mode is ios::in | ios::out, when you specified the mode as binary, but nothing for input or output, you ended up with what...?

Try creating it with output mode.

fstream fout("D:\\pt_data.bin", ios::binary | ios::out);
Topic archived. No new replies allowed.