The problem I am facing is the following:
if we define something like
ofstream myFile;
myFile.open("Directory//debug.txt");
for (int i = 0; i < 10; i++)
{
myFile << i << endl;
myFile.close();
}
the output in the debug file will be 9.
I want to make it so that it outputs all the numbers from 0 to 9. Aside from closing the file after the for statement is it possible to define an ofstream that would do that?
No. You have two options:
Close the file outside the loop:
myFile.open("Directory//debug.txt");
for (int i = 0; i < 10; i++)
{
myFile << i << endl;
}
myFile.close();
or open the file in append mode and close inside the loop:
for (int i = 0; i < 10; i++)
{
myFile.open("Directory//debug.txt", ios_base::app);
myFile << i << endl;
myFile.close();
}
myFile.close();
should be put after the for-loop. Also introduce some error checking to see if the open was indeed a success.
I am calling a function foo repeatedly in a function goo I create the
file in foo and I want to output a new value each time foo is called
in goo.
In order to achieve your objective you could use a static variable inside foo
void foo()
{
static int count=0;
ofstream myfile;
myfile.open("Directory//debug.txt",std::fstream::app)
if (myfile.is_open()) // Checking is file is successfully opened.
{
count++;
myfile<<count<<"\n";
}
myfile.close; // Close the file
}
Related
I am attempting to read numbers from a text file into a program, but for some reason, the program isn't reading the file. Here is my code:
#include <iostream>
#include <stream>
using namespace std;
int main()
{
ifstream infile;
infile.open ("adventDay1.txt");
if (!infile) { //Check if file is opening
cerr << "Error!"<< endl;
return 0;
}
int dataSize = 0;
infile >> dataSize;
int* arr;
arr = new int[dataSize]; //dynamically allocated array
int measureCount = 0; //Keep track of input from file
for (int i = 0; i < dataSize; i++) {
// infile >> dataSize;
arr[i] = dataSize;
measureCount += 1;
}
cout << measureCount << endl;
delete[] arr; //Delete dynamically allocated memory
return 0;
}
Each time I run it, it just displays the "Error!" message I added. There are 2,000 numbers in the text file, so that should be the expected output based on what I have here. I can't pinpoint the mistake.
Include fstream and ensure that you are opening the file in read mode. Perhaps also define it as ifstream infile("adventDay1.txt")
I must be missing something simple here, but I am trying to write and read a binary file in C++.
ofstream file3("C:\\data2.txt", ios::out | ios::binary);
for (int i = 0; i < 100; i++) {
file3.write((char*)(&i), sizeof(int));
}
ifstream file4("C:\\data2.txt", ios::in | ios::binary);
int temp;
while (!file4.eof()) {
file4.read((char*)(&temp), sizeof(int));
cout << temp << endl;
}
The file looks like it is getting created properly when viewed with a hex editor. However, as I go to read the file it reads 1 random junk value and quits vs. listing out all the numbers.
Update
I made a slight update based on the comments and all seems good now. On Windows the close made a difference and I did fix the loop condition.
ofstream file3("C:\\data2.txt", ios::out | ios::binary);
for (int i = 0; i < 100; i++) {
file3.write((char*)(&i), sizeof(int));
}
file3.close();
ifstream file4("C:\\data2.txt", ios::in | ios::binary);
//cout << file4.eof();
int temp;
while (!file4.read((char*)(&temp), sizeof(int)).eof()) {
cout << temp << endl;
}
You might not have permission to write to c:\\file, so you should check if you can. As for using .eof() see this topic. Finally, you might want to close the file before you open it again for reading. Here is your example tweaked:
#include<iostream>
#include<fstream>
int main()
{
std::ofstream file3("data2.txt", std::ios::binary);
if (file3)
{
for (int i = 0; i < 100; i++)
{
file3.write((char*)(&i), sizeof(int));
}
file3.close();
}
std::ifstream file4("data2.txt", std::ios::binary);
int temp;
while (file4)
{
file4.read((char*)(&temp), sizeof(int));
std::cout << temp << std::endl;
}
}
Demo: http://coliru.stacked-crooked.com/view?id=8f519fcd05879855
I'm working with visual studio 2013. I want to output a vector of objects into several files. I am able to create the output file if I just print everything to a single file, but if I try to output to multiple files, nothing happens.
#include<vector>
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
struct object
{
int a, b;
};
int main()
{
vector<object> DATA;
//fill DATA
ofstream out; string outname;
outname = "TL" + ".txt";
out.open(outname.c_str());
for (int i = 0; i < p; i++)
{
for (int k = 0; k < DATA.size(); k++)
{
out << i << endl;
if (DATA[k].a == i)
out << DATA[k].b << endl;
}
out << endl;
}
out.close();
return 0;
}
The above works exactly as I expect. However, if I rearrange it so that I could make separate files:
for (int i = 0; i < p; i++)
{
ofstream out; string outname;
outname = "TLR" + to_string(i) + ".txt";
out.open(outname.c_str());
for (int k = 0; k < DATA.size(); k++)
{
if (DATA[k].a == i)
out << DATA[k].b << endl;
}
out.close();
}
I get no output. I already checked to see if the files were being created in another directory and nada. Placing "cout << out.is_open()" after each of the cases shows that the single file is actually being opened (output 1), while the multiple files are not being opened (output 0).
Could anyone tell me what's going on and what can I do to fix this? I don't want to have to run the program and then open the output file to parse after I've made it.
Thank you.
When I was making the multiple files, I used the pipe, "|", (not shown) in the filename--which is a forbidden character in Windows' filenames.
I'm reading the individual lines from a text file and attempting to print them out on individual lines in the command prompt, but the text just flashes really quickly and disappears.
I is set to the number of lines in readable.txt
cout << "These are the names of your accounts: " << endl;
for (int b = 1; b <= i; b++)
{
fstream file("readable.txt");
GotoLine(file, b);
string line;
file >> line;
cout << line << endl;
}
cin.ignore();
break;
Any help would be greatly appreciated.
error:
Opening a fstream inside a loop? that is suicide, your fstream is always the same why are you opening it for every iteration?
The text probably disappears because your program reaches the end and auto exits you should make him wait before the break or before it reaches the end
You don't need to reopen file every time and invoke GotoLine(file, b); you can open it once outside the for loop and read strings via std::getline(file, line).
If you want to watch the output, insert system("pause") just after the for loop. If you want to pause input after each line, insert getchar() in the end of the for loop (inside of it)
Firstly avoid opening a file inside a for loop. You are doing a lot of mess here.
Try this code
std::ifstream file("readable.txt");
file.open("readable.txt");
if(file.fail())
{
std::cout << "File cannot be opened" << std::endl;
return EXIT_FAILURE;
}
std::string line;
while std::getline(file, line) // This line allows to read a data line by line
{
std::cout << line << std::endl;
}
file.close();
system("PAUSE"); // This line allows the console to wait
return EXIT_SUCCESS;
The break is nonsense (if the snippet is not in a loop or switch.
My guess for the disappearing text is an interference with a IDE. Try it in a terminal/console.
And as in the other answers, file open should be outside the loop.
#include <iostream>
#include <fstream>
using namespace std;
void GotoLine(fstream &f, int b)
{
char buf [999];
while (b > 0) { f.getline (buf, 1000); b--; }
}
int main ()
{
int i = 5;
cout << "These are the names of your accounts: " << endl;
for (int b = 1; b <= i; b++)
{
fstream fl("readable.txt");
GotoLine(fl, b);
string line;
fl >> line;
cout << line << endl;
}
}
I'm relatively new to C++ and programming in general, so I'm guessing that my mistake is a pretty simple one. Anyways, I've been working on scanning DNA sequences in from .txt files and I am trying to program it such that the user can specify the names of the data files from the command line. I included the entire function for reference, however the particular problem I'm getting is that I've been unable to get the file to actually open, the program always returns the "Unable to open file" message. The part with which I am having problems (I think) is the last for loop, but I included the entire function for reference.
int dataimport (int argc, char* argv[]){
vector<string> mutationfiles (argc -1); //mutationfiles: holds output file names
vector<string> filenames (argc - 1); //filenames: holds input file names
if (argc > 1){
for ( int i = 1; i < argc; ++i){
string inputstring = argv[i]; //filename input by user
filenames[i-1] = inputstring; //store input filename in vector
stringstream out;
out << inputstring << "_mutdata.txt"; //append _mutdata.txt to input file names
mutationfiles[i-1] = (out.str()); //store as output file name
inputstring.clear(); //clear temp string
}
}
else{
cout << "Error: Enter file names to be scanned" << endl;
system("PAUSE");
return EXIT_FAILURE;
}
for(int repeat = 0; repeat < argc; ++repeat){
ifstream myfile; //open input file
myfile.open (filenames[repeat].c_str());
ofstream myfile2; //open output file
myfile2.open (mutationfiles[repeat].c_str());
string all_lines;
if (myfile.is_open()){
while ( myfile.good() ){ //scan data
getline (myfile,all_lines,'\0');
}
myfile.close(); //close infile
}
else{ //error message
cout << "Unable to open file\n";
system("PAUSE");
return EXIT_FAILURE;
}
}
}
Please let me know if there is any additional information you need or anything I should research so that I can better help myself!
for(int repeat = 0; repeat < argc; ++repeat)
should be
for(int repeat = 0; repeat < argc - 1; ++repeat)
Aside from that I can't see anything that would cause the error you are getting.
If you fix that and still get errors, I would try printing the names to make sure the contents of your two vectors is correct.
for(int repeat = 0; repeat < argc - 1; ++repeat)
{
cout << filenames[repeat] << endl;
cout << mutationfiles[repeat] << endl;
}
Change for ( int i = 1; i < argc; ++i) to for ( int i = 0; i < argc; i++)
and
change filenames[i-1] = inputstring; to filenames[i] = inputstring;
and
change mutationfiles[i-1] to mutationfiles[i].