Files created in C++ can't be found [duplicate] - c++

This question already has answers here:
C++: Where does the ofstream class save the files to?
(4 answers)
Closed 8 years ago.
I want to use C++ to create files which I can then export for use elsewhere. The following code seems to create files okay, in the sense that I can write data into the file and then read it again later in a C++ program. When I try to actually find created file so as to use it, however, it is nowhere to be found..
using namespace std;
int main () {
ofstream myfile ("example3.dat");
if (myfile.is_open()){
myfile << 3335 << " " << 64 << " " << 43 << 9 << 5 << 6 << 5 << 4 << 6;
myfile.close();
}
else cout << "Unable to open file";
ifstream myfile2 ("example3.dat");
int b;
myfile2 >> b; cout <<b;
myfile2 >> b; cout <<b;
myfile2.close();
return 0;
}

The files will be created in the process working directory.
In case the process is being run from an IDE (e.g. Visual Studio), the working directory can be different from the executable file path. You should check the project properties to find out the actual path.

Certainly you can search for the file as suggested in comments above, but you might be better off specifying an absolute path in your program, so that you know where it's being written.
The formatting of the path is OS-specific, but maybe
/tmp/example.dat
C:\Windows\Temp\example.dat
for Linux and Windows respectively (but you will need to decide for yourself; these are just examples).

Related

strange thing in sequential file access

Recently, I am trying to write codes to get trained in sequential file access. I learned it well, but the issue is kinda stressing me out. I have a code that work 100%, and its task is "make a code that prints array elements inside a file", the text file name is "numric".
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int a[3]={5000,6000,7000};
ofstream outfile("numric.txt");
if (outfile.is_open()){
outfile << "employee payroll:" << endl;
for (int i=0;i<3;i++)
outfile << a[i] << endl;
outfile.close();
} else
cout << "failed!" << endl;
return 0;
}
I implemented the code in two different program (VS Code, dev++) and it works fine. It found the file, but when I open the text file, there isn't any text inside it. The code should do its work by finding some text inside it if I opened it.
Note:sometimes when the code works, the antivirus pops a message saying it found an item that doesn't look safe in the program and deletes it.

While reading form a file, how to account for new lines after using the << operator? [duplicate]

This question already has answers here:
C++ Ignore Empty First Line
(2 answers)
Using getline(cin, s) after cin [duplicate]
(13 answers)
Closed 6 years ago.
I am having trouble reading in double values into an array from a file
after the first iteration of the for loop, there is no more reading due to the newline character. How can I bypass this issue?
Sample of input file:
word
2.55
word <---as of now this will not read
5.66
file.open("productsIn.txt");
if(!file.is_open()){
cout << "Could not open file." << endl;
return 1;
}
if(file.is_open()){
cout << "file open" << endl;
for(int i = 0; i < MAX_COUNT; i++){
getline(file, productName[i]);
file >> prices[i];
if(file.good()){
cout << productName[i] << endl << prices[i] << endl;
}
}
}
file.close();
If your data consists of alternating lines of names and prices like this:
item 1
1.50
item2
2.50
...
You can of course simply call another getline() after reading the float. It will read away the newline which is at the read position, and clear the dummy string argument which can be ignored. It kind of makes sense because you do read two lines, so you may need two getlines. (You could do without the getline() after the name because the formatted input for the price will skip whitespace; but I guess the EOL is the marker for "end of name", where a name may consist of more than one word.)
You can also use ignore or ws as suggested in this complete answer.
Because the data is actually line oriented it may be clearer to follow Pete Becker's suggestion and read all lines via getline(), parsing the ones which need it — like the prices — simply via a [i]stringstream.

C++ will not create a file to output text to?

So, what I have here is a simple snippet of C++ code that merely askes for a filepath, checks if the filepath exists, and if it does, the program closes. If it doesn't, it creates a file and writes text to it. The path I enter is C:\temp.txt, but no matter which path I use the result is the same: No file is created. I am using Visual Studio 2010.
string outFile = "";
cout << "Enter a file path for an output file that does not exist already: ";
cin >> outFile;
ofstream file_writer;
file_writer.open(outFile, ios::out);
if (file_writer.good()) {
cout << "This file exists already!" << endl;
system("PAUSE");
return 255;
}
else
file_writer << "Hello";
file_writer.close();
You could try:
string outFile = "";
cout << "Enter a file path for an output file that does not exist already: ";
cin >> outFile;
ofstream file_writer;
file_writer.open(outFile, ios::in);
if (file_writer.good()) { //This now just checks if the file exists already
cout << "This file exists already!" << endl;
system("PAUSE");
return 255;
}
file_writer.open(outFile, ios::out); //Now since we know the file doesn't exist, we can create it safely
if (!file_writer.good()) {
cout << "Failed to create file!" << endl;
return 254;
}
file_writer << "Hello";
file_writer.close();
Check your fail() error message:
if (outfile.fail())
cout << strerror(errno) << endl;
You cannot write to "C:".
Try with a different path, and it should work.
Nice! ofstream::good() returns true if no error occurs. Use a negation in the if-condition.
if (!file_writer.good()) {
...
}
This response may be a little late, but I just spend two days figuring out why Visual Studio C++ was not creating any text files.
I'm going through Wrox Professional C++ Fourth Edition. In chapter 13 on the section for file streams, I could not get any examples to work. I spent many hours downloading sample code with the same results.
I then looked at my anti-virus software. There are two settings in there that caught my eye: Folder Access, and Exclusions. I'm running Windows Security on Widows 10. I changed Exclusions to prevent the security software from monitoring my vs2019 folder and subfolders. No improvement.
I then looked at the parent folder c:\files. This had folder access enabled. I removed this and everything worked fine. Instead of putting folder access on the entire files folder, I enabled it on the specific subfolders omitting the vs2019 folder. I hope this save somebody many frustrating hours.

How do I make a C++ program that opens another program? [duplicate]

This question already has answers here:
How to get the current user's home directory in Windows
(4 answers)
Closed 7 years ago.
So I know how to make it, I just want it to open the file without specifying the path.
For example: I have it in
C:\Users\\(me)\Desktop\Projects\BCs\BSCV2\bin\Debug\BSC.exe
but if I give it to a friend, he has a different username, (him) for example, so the command won't be able to execute even if he has it on his desktop because the path isn't valid anymore.
Here's a part of the code:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int a;
cout << endl;
cout << " This window is used for launching the programs." << endl;
cout << " Type in the number of the program you want to use and press Enter." << endl;
cout << endl;
cout << " 1) BSCV2 << endl;
cout << endl;
cout << " "; cin >> a; cout << endl;
cout << endl;
if (a == 1){
system ("start C:\\Users\\(me)\\Desktop\\Projects\\BCs\\BSCV2\\bin\\Debug\\BSCV2.exe");
system ("pause");
}
return 0;
}
How can I make it run on anyone's PC, regardless of where they put it?
Also, if you could re-write my code as an example, I'd appreciate it.
You will need to get the "home" directory for the current user logged in. Reference this post: How to get the current user's home directory in Windows, or this one: How can I find the user's home dir in a cross platform manner, using C++?
However, are you absolutely sure that all users (on their respective machines) running your application will have the exact directory path to the executable you're trying to call (\Desktop\Projects\BCs\BSCV2\bin\Debug\BSCV2.exe)?
You may be better off writing a function to search for the executable, or ask the user to specify where it is.

Difficulty reading binary files in c++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a visual c++ project named Search Elements in which there is a class called PeriodicTable and I have another visual c++ project called Write Elements in which there is this same class and it's description(variable names and their sizes) is same too...
I use the Write Elements project to write the object of the class Periodic Table to a binary file named PeriodicTable.dat but whenever I use the binary file with my Search Elements project(basically just copy-paste from Write Elements to Search Elements) then the output is unexpected(contains garbage value).
In my opinion the file should work with both the projects as both the projects contains the same class decription. But I don't know what is the problem???
Write Elements Code:
#include <iostream>
#include <fstream>
using namespace std;
class PeriodicTable
{
char Name[15], Symbol[3], Block, State[10], Colour[15], Classification[20];
int GroupNo, AtomicNo, PeriodNo;
float Weight;
public:
void GetInfo();
};
int main()
{
PeriodicTable ptele;
ofstream fileout;
fileout.open("PeriodicTable.dat", ios::binary | ios::app);
system("cls");
ptele.GetInfo();
fileout.write((char *)&ptele, sizeof(ptele));
fileout.close();
return 0;
}
void PeriodicTable::GetInfo()
{
cout << "Full Name of the element: ";
cin >> Name;
cout << "Symbol: ";
cin >> Symbol;
cout << "Block: ";
cin >> Block;
cout << "State(at Room Temperature): ";
cin >> State;
cout << "Colour: ";
cin >> Colour;
cout << "Classification: ";
cin >> Classification;
cout << "Group Number: ";
cin >> GroupNo;
cout << "Atomic Number: ";
cin >> AtomicNo;
cout << "Period Number: ";
cin >> PeriodNo;
cout << "Atomic Weight: ";
cin >> Weight;
}
You did not perform class abstraction correctly. And more over, everything in same file? including class definition? That's not how you use VS project structure.
I assume you want to create two separate applications. One would create periodic table and a second application use the file generated by first application.
If above is correct, you need to declare the PeriodicTable class in header, implement constructor, destructor and GetInfo method in a .cpp implementation. Another .cpp implementation should contain your main() function for the first application.
Note that it is generally a good idea to create a universal header file in a shared location by two applications which contain global definitions, like the path to the generated .dat file. In this case, absolute path should be taken as both applications will unlikely have same relative path to the file.
Another thing to notice, instead of letting compiler figure out how the file should be structured, structure it yourself. Follow the structure convention you created in both application. One suggestion is that instead of writing (char *) &ptele, write one line for one element, give a tab between each column, say between Element and Symbol. You'll need to parse it properly before using the value but this avoids any ambiguity of the data.
It perfectly works for me with the following read code:
int Read()
{
ifstream file;
file.open("PeriodicTable.dat", ios::binary | ios::in);
while (0 == file.rdstate())
{
PeriodicTable ptele;
file.read((char *)&ptele, sizeof(ptele));
//if (0 == file.rdstate())
// ptele.PrintInfo();
}
file.close();
return 0;
}
I do not think you use the VS project structure correctly. At the first sight your simple solution should contain one project that would contain one class (PeriodicTable) and this class should have several methods e.g. searchElements, writeElements, readElements etc. What is wrong with this approach? If, for some reason, you cannot use this approach, then I think you should better explain your problem, what you are trying to achieve.