I'm having trouble with fstream not writing to my file when it is located in a specific place. In the following code when the commented line is uncommented the file is written to, however when it is commented the file is not written to at all. I've added a bunch of console output and it says both of the outputs around the "outputFile << newWord << endl;" are completed but the file is never actually written to.
void write_index( string newWord )
{
fstream outputFile( "H:\\newword.txt", ios::app );
int same = 0;
string currWord;
currWord.resize(5);
//outputFile << newWord << endl;
while( !outputFile.eof() )
{
getline( outputFile, currWord );
cout << "Checking if " << newWord << "is the same as " << currWord << endl;
if( newWord == currWord )
{
cout << "It is the same" << endl;
same = 1;
break;
}
}
if( same != 1 )
{
cout << "Writing " << newWord << "to file" << endl;
outputFile << newWord << endl;
cout << "Done writing" << endl;
}
outputFile.close();
}
I'm somewhat confident you're looking for something along these lines:
void write_index( const string& newWord )
{
fstream outputFile( "H:\\newword.txt", ios::in);
bool same = false;
if (outputFile)
{
string currWord;
while (getline(outputFile, currWord))
{
cout << "Checking if " << newWord << " is the same as " << currWord << endl;
same = (newWord == currWord);
if (same)
{
cout << "It is the same" << endl;
break;
}
}
}
if (!same)
{
outputFile.close();
outputFile.open("H:\\newword.txt", ios::app);
cout << "Writing " << newWord << "to file" << endl;
outputFile << newWord << endl;
cout << "Done writing" << endl;
}
outputFile.close();
}
There are better ways to do this, but that will likely be a decent place to start.
Related
I'm trying to read in the database down below into a vector of strings while removing the header lines (lines with >db) and imputing each sequence below it into a string.
This is the code I have right now:
void read_in_database_file(string db_file) {
ifstream fin;
fin.open(db_file);
if (!fin.is_open())
{//if
cerr << "Error did not open file" << endl;
exit(1);
}//if
vector<string> database;
string line = "";
while(getline(fin, line, '>'))
{
database.push_back(line);
}
finding_kmers(database);
}
int main() {
cout << "\n" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "------------------------------------ BLAST -----------------------------------" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << endl;
cout << "Welcome to BLAST" << endl;
cout << "Please enter the name of your datafile" << endl;
string db_file = "";
getline(cin, db_file);
cout << endl;
read_in_database_file(db_file);
}
Currently, all it does is simply remove the ">" but print that line and everything else as is. How do i solve this?
database file:
>db_1
GATCTTGCATTTAGAAAATCATAAGAAATTTACTAAAAAGTATTAGGACTCATGAACAAATTTAAGAATG
TAACACTATATAAGATTGGTATACAAAAATAACTGTACTTCTTCACCAAGAAATCAAGAATCCAAAAATG
>db_2
TAGTTTGTTCTAGGATTTATGTGTTTCCTTAAAGTCTTAGTTTGATTATGTTACATTTAGCATGAGTGAC
TCCATTTTGGTTTGGTTTGGTCTGTTGGGACCTATTGCATGAGTTTAGTTCAAAACAATGGCCTCCCATA
>db_3
TTGTCCTTGCGATAGTTTACTGAGAATGATGATTTCCAATTTCATCCATATCCCTACAAAGGACATGAAC
TCATCATTTTTTATGGCTGCATAGTATTCCATGGTGTATATGTGCCATAATTTCTCAATCCAGTCTATCG
This function is to count the number of lines in my text file
int counter()
{
int counter = 0;
ifstream infile("books.txt", ios::in);
if (infile.is_open() && !infile.eof())
{
char line[200];
while (!infile.eof())
{
infile.getline(line, 200, '\n');
counter++;
}
infile.close();
}
else
cout << "File is not open\n";
return counter;
}
This is my search function where it reads data in from text file "books.txt" into array of struct - DATA book. But I couldn't figure which part is wrong and makes it show "Record not found" even if I entered the correct input. DATA book is my array of struct to store whatever is in the text file and categorized them into members like isbn code, author, title etc.
int search(DATA book[])
{
char search[200];
int i = 0;
bool found = false;
cout << "Enter ISBN Code/title/author to SEARCH: ";
cin.getline(search, 200);
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
int count = counter();
while (i < count && !found)
{
if (strcmp(search, book[i].isbn_code) == 0 || strcmp(search, book[i].author) == 0 || strcmp(search, book[i].title) == 0)
{
found = true;
cout << "ISBN Code: " << book[i].isbn_code << "\nAuthor: " << book[i].author << "\nTitle: " << book[i].title << "\nPublisher: " << book[i].publisher
<< "\nYear Published: " << book[i].year_published << "\nQuantity: " << book[i].quantity << fixed << setprecision(2)
<< "\nPrice: " << book[i].price << "\nRack: " << book[i].loc.rack << "\nLevel number: " << book[i].loc.level_no << endl << endl;
}
else
i++;
}
if (!found)
cout << "Record not found.\n";
return 0;
}
I have a c++ program that wries a simple json file using ofstream.
if( GDALGetGeoTransform( m_dataset, adfGeoTransform ) == CE_None )
{
cout <<std::fixed << std::setprecision(3) << adfGeoTransform[0] << ", "<< adfGeoTransform[1] << ", "<< adfGeoTransform[2] << ", "<< adfGeoTransform[3] << ", "<< adfGeoTransform[4] << ", "<< adfGeoTransform[5] << ", "<<endl;
ofstream myfile;
myfile.open ( outPath + "/tiles.json");
myfile << std::fixed << std::setprecision(9) ;
myfile << "{" <<endl;
myfile << "\"title\": \"" << filename << "\"," << endl;
myfile << "\"ul\" : [" << dfGeoX<<", "<< dfGeoY<<"]," << endl;
myfile << "\"lr\" : [" << dfGeoX1<<", "<< dfGeoY1<<"]," << endl;
myfile << "\"res\" : [" << adfGeoTransform[1]<<", "<< adfGeoTransform[5] <<"]," << endl;
if( m_dataset->GetProjectionRef() != NULL )
{
//printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );
myfile << "\"projection\" : \"";
auto proj = m_dataset->GetProjectionRef();
for(int i =0 ; proj[i] != '\0';i++){
if(proj[i] == '"')
myfile << '\\';
myfile << proj[i];
}
myfile << "\"," << endl;
}
myfile << "\"maxZoom\" : "<< max(ceil(log2(nRows / tileSize)), ceil(log2(nCols / tileSize))) << endl;
myfile << "}" <<endl;
myfile.flush();
myfile.close();
}
I do see the console output from cout, so it is entering the if branch.
But funny thing is that when i run it the first time it do not generate tiles.json file. But running it again it creates the file.
The problem was that the folder that it was trying to create the file in did not exist.
The application did not crash due to this, just continued and then later in the application the folder was created by 3th party lib as a output of other files generated.
Then running the second time, the folder exists and the file is written.
I have a problem with file handling. More precisely I've written a code for exercising but after a time it won't make the .txt file.
I don't know if the error is my computer or my code but I hope someone knows the answer.
It's not the final stage but the problem started here.
(This is a simple console application)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int Counter()
{
static int taskID;
cout << taskID++ << " - ";
}
int main(int argc, char const *argv[])
{
char inputTask[256];
string outputTask;
string listAllTask = "-l";
string addNewTask = "-a";
string removeTask = "-r";
string completeTask = "-c";
if (argc == 1) {
cout << "CLI Todo application" << endl;
cout << "====================\n" << endl;
cout << "Command line arguments:" << endl;
cout << "-l Lists all the tasks" << endl;
cout << "-a Adds a new task" << endl;
cout << "-r Removes a task" << endl;
cout << "-c Completes an task" << endl;
} else if (argc == 2) {
//create an object to access the file that containing the tasks
fstream todoApp("tasks.txt", ios::ate | ios::in | ios::out);
if (todoApp.is_open()) {
if (string(argv[1]) == listAllTask){
while (!todoApp.eof()) {
todoApp.seekg(0, ios::end);
if (todoApp.tellg() == 0) {
cout << "No todos for today! :)" << endl;
} else {
getline(todoApp, outputTask);
cout << Counter << outputTask << endl;
}
}
} else if (string(argv[1]) == addNewTask) {
cout << "Enter the new todo:" << endl;
todoApp.seekg(0, ios::end);
cin.getline(inputTask, 120);
todoApp << inputTask << endl;
todoApp.close();
cout << "-- your task has been saved --" << endl;
}
} else {
cerr << "Something went wrong, please, try again." << endl;
}
//todoApp.close();
} else {
cout << "Too many arguments!!!" << endl;
}
return 0;
}
I have a class that's supposed to write to a gml file defined below. The class has one method that does the writing. If I call the function, I get a core dump when the main function returns. I can create objects of the class with no problem, it only happens when the write function is called. The function also returns with no error and the rest of the program runs.
GML Writer:
class GMLWriter {
public:
void write(List<User*> usr, const char* filename);
};
void GMLWriter::write(List<User*> usr, const char* filename)
{
cout << "Filename: " << filename << endl;
ofstream outfile;
outfile.open(filename);
if (!outfile.is_open())
cout << "Couldn't open the file..." << endl;
outfile << "graph [\n";
// Write user data
for (int n = 0; n < usr.size(); n++) {
cout << "Writing node..." << endl;
outfile << "node [\n";
outfile << "id " << usr[n]->getID() << "\n";
outfile << "name \"" << usr[n]->getName() << "\"\n";
outfile << "age " << usr[n]->getAge() << "\n";
outfile << "zip " << usr[n]->getZip() << "\n";
outfile << "]\n";
}
// Write associations
for (int n = 0; n < usr.size(); n++) {
List<int> tList = usr[n]->getFriends();
cout << "Writing edge..." << endl;
//List<int> tempL = usr[n]->getFriends();
for (int i = 0; i < tList.size(); i++) {
outfile << "edge [\n";
outfile << "source " << usr[n]->getID() << "\n";
outfile << "target " << tList[i] << "\n";
outfile << "]\n";
}
}
outfile << "]"; // end graph
cout << "End function" << endl;
outfile.close();
}
User simply contains the variables to write to the file, and those methods work fine.
I've spent hours with this in a debugger and haven't been able to find the problem. Any help would be greatly appreciated.
Thanks!
Try looking at the core dump: http://www.network-theory.co.uk/docs/gccintro/gccintro_38.html