Here is the minimal reproducible code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string TEST_FILE_PATH = "output.txt";
void write_to_file(string path, string line);
void generate_passwords(string file);
int main()
{
generate_passwords(TEST_FILE_PATH);
return 0;
}
void generate_passwords(string file)
{
int count = 1;
for (int len = 1; len <= 100; len++)
{
for (int i = 0; i < 100; i++)
{
write_to_file(file, to_string(count) + " : ");
count++;
}
}
}
void write_to_file(string path, string line)
{
ofstream file;
file.open(path, ios::out | ios::app);
cout << "writing line : " << line << endl;
if (file.is_open())
{
cout << "file is open " << endl;
file << line << '\n';
cout << "written..." << endl;
}
else {
cout << "FILE NOT OPEN" << endl;
}
file.close();
}
This is a stripped-down version of my full code, and it reproduces the same error.
With this code, I expect exactly 10,000 lines to be written to output.txt. However, it sometimes skips a random number of lines:
See how it skips numbers 6466 to 6509.
The console prints "FILE NOT OPEN" for these numbers.
This rarely happens with fewer iterations, but occurs very often with large numbers of iterations.
What could be the issue?
Related
I think this is a pretty simple question, but I didn't find the answer.
I wish to write the result of a function to a file.
The file is open, and I'm able to write a simple string to it, but not the result of the function.
What I am missing?
#include <iostream>
#include <fstream>
using namespace std;
void addingtext(){
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
}
}
int main () {
ofstream file;
file.open("example.txt");
if(file.is_open()){
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext();
//file << addingtext;
file.close();
return 0;
}
addingtext() returns nothing, and writes to std::cout.
You have two options:
Option 1: Make addingtext() return a string, and then write that to the file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::string addingtext() {
std::string result;
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
result += i;
result += "\n";
}
return result;
}
int main() {
ofstream file;
file.open("example.txt");
if (file.is_open()) {
std::cout << "File Open Access \n";
}
file << "Write this to the file";
file << addingtext();
file.close();
return 0;
}
Option 2: Make addingtext() write to the file:
#include <iostream>
#include <fstream>
using namespace std;
void addingtext(ofstream& o) {
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
o << i << endl;
}
}
int main() {
ofstream file;
file.open("example.txt");
if (file.is_open()) {
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext(file);
file.close();
return 0;
}
Your function does not return any value.
If it returned a value, such as a string you have created during the running of the addingtext function you could then add that string straight to the file as you are doing there.
I think you want to pass the file stream to your function so it writes to the file instead of std out.
void addingtext(ofstream& stream){
for (int i = 0; i < 8; ++i)
{
stream << i << endl;
}
}
int main () {
ofstream file;
file.open("example.txt");
if(file.is_open()){
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext(file);
//file << addingtext;
file.close();
return 0;
}
If you want your function to return a string, don't declare it's return type as void. I would:
#include <string>
string addingtext(){
string temp;
for (int i = 0; i < 8; ++i)
{
temp += i;
}
return temp;
}
I am trying to read from a .csv file. There are two functions below, one for writing and one for reading.
The file contains a simple table:
date,first,second
1 a one
2 b two
3 c three
4 c four
For some reason, the statement while(file_stream.read(&c,1)); does not read anything. It stops at the first character and I'm dumbfounded as to why. Any clues?
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
std::string filename;
std::string line_string;
ifstream file_stream;
stringstream ss;
vector< vector<string> > vec;
char c;
void read_file()
{
filename = "test.csv";
cout << filename << endl;
file_stream.open(filename.c_str(),ios::out|ios::binary);
if(file_stream.fail())
{
cout << "File didn't open" << endl;
return;
}
if(file_stream.is_open())
cout << "file opened" << endl;
while(file_stream.read(&c,1)); // this isn't working
{
cout <<"char c is: " << c;
ss << noskipws << c;
}
file_stream.close();
cout << "string is: " << ss.str() << endl;
//get each line
int counter = 0;
vector<string> invec;
while(getline(ss,line_string,'\n'))
{
string header_string;
stringstream header_stream;
header_stream << line_string;
while(getline(header_stream, header_string,','))
{
invec.push_back(header_string);
}
invec.push_back(header_string);
vec.push_back(invec);
invec.clear();
counter++;
}
}
void test_output()
{
for(int i = 0; i < vec.size();i++)
{
for(int in = 0; in < vec[0].size(); in++)
cout << vec[i][in] << " ";
cout << endl;
}
}
int main()
{
read_file();
test_output();
}
Look very very carefully at the line that is not working:
while(file_stream.read(&c,1)); // this isn't working
{
cout <<"char c is: " << c;
ss << noskipws << c;
}
The ; character at the end of the while statement does NOT belong! You are running a no-body loop that does not terminate until read() fails, and THEN your code enters the bracketed block to output the last character that was successfully read (if any).
You need to remove that erroneous ; character:
while(file_stream.read(&c,1)) // this works
{
cout <<"char c is: " << c;
ss << noskipws << c;
}
Now, the real question is - why are you reading the input file character-by-character into a std::stringstream in the first place? You can use std::getline() with the input std::ifstream directly:
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
std::vector< std::vector<std::string> > vec;
void read_file()
{
std::string filename = "test.csv";
std::cout << filename << std::endl;
std::ifstream file_stream;
file_stream.open(filename.c_str(), ios::binary);
if (!file_stream)
{
std::cout << "File didn't open" << std::endl;
return;
}
std::cout << "file opened" << std::endl;
//get each line
std::vector<std::string> invec;
std::string line;
int counter = 0;
if (std::getline(file_stream, line))
{
std::istringstream iss(line);
while (std::getline(iss, line, ','))
invec.push_back(line);
vec.push_back(invec);
invec.clear();
++counter;
while (std::getline(file_stream, line))
{
iss.str(line);
while (iss >> line)
invec.push_back(line);
vec.push_back(invec);
invec.clear();
++counter;
}
}
}
void test_output()
{
if (!vec.empty())
{
for(int in = 0; in < vec[0].size(); ++in)
std::cout << vec[0][in] << ",";
std::cout << std::endl;
for(int i = 1; i < vec.size(); ++i)
{
for(int in = 0; in < vec[i].size(); ++in)
std::cout << vec[i][in] << " ";
std::cout << std::endl;
}
}
}
int main()
{
read_file();
test_output();
}
I want to create small program to understand things I need better.
This code can write words to text document, new line under previous in sequential order and keep lines there after starting program again.
Now before adding a new word or phrase to the file, I want to find if the word already exists in my document, if exist, don't add it, but get exist equal one on output, read it from file, and main thing here is somehow also find line under or above current exist line. For example: if exist line index is 3, I want to see +1 line 4 or -1 line 2. If new word doesn't exist in text document just add it.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::ofstream outfile("doc.txt", std::ios_base::app);
int main()
{
std::string t;
for (int i = 0; i < 10; i++)
{
cout << "Add new phrase: " << endl;
std::getline(std::cin, t);
cout << t << endl;
outfile << t << std::endl;
}
_getch();
return 0;
}
EDIT:
using namespace std;
std::ofstream outfile("doc.txt", std::ios_base::app);
int main()
{
int length = 100;
std::ifstream infile("doc.txt", std::ifstream::in);
infile.seekg(0, infile.end);
size_t len = infile.tellg();
infile.seekg(0, infile.beg);
char *buf = new char[len];
infile.read(buf, length);
infile.close();
std::string writtenStr(reinterpret_cast<const char *>(buf), len);
std::string t;
for (int i = 0; i < 10; i++)
{
std::getline(std::cin, t);
if (writtenStr.find(t) != std::string::npos)
{
cout << "Line [" << t << "] exist." << endl;
}
else
{
cout << "Line [" << t << "] saved." << endl;
writtenStr += t;
outfile << t << std::endl;
}
}
_getch();
return 0;
}
I'd read the file into a string when the program starts. Then, check the string for the phrase each time i want to add a new word. If the string doesn't contain the phrase, add it to the string and the file, and a delimiter of your choice if desired. For example:
int main()
{
// Read existing file into a string
std::ifstream infile("doc.txt", std::ifstream::in);
infile.seekg(0, infile.end);
size_t len = infile.tellg();
infile.seekg(0, infile.beg);
char *buf = new char[len];
infile.read(buf,length);
infile.close();
std::string writtenStr(reinterpret_cast<const char *>(buf), len);
// Open file for output
std::ofstream outfile("doc.txt", std::ios_base::app);
std::string t;
for (int i = 0; i < 10; i++)
{
// Get new phrase
std::getline(std::cin, t);
// Check if phrase is already in file;
if (writtenStr.find(t) == std::string::npos)
{
cout << "Could not add new phrase: " << endl;
cout << t << endl;
cout << "Phrase already exists in file." << endl;
}
else
{
cout << "Add new phrase: " << endl;
cout << t << endl;
writtenStr += t;
outfile << t << std::endl;
}
}
_getch();
return 0;
}
I'm trying to read in a random file (on mac-xcode) and determine the instances of the letter k in the document. Then print the number as an outout file. My problem is that the outfile isn't being written and the nums_k is coming back as 0. I'm not sure if the ifstream is working incorrectly or the ofstream need a different filename established. Here's my source code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("Users/bryanmichaelnorris/documents/extra credit assignment.docx");
string line;
int numks = 0;
while (getline(infile,line)) {
int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k') {
numks++;
}
x++;
}
}
infile.close();
ofstream outfile("number of k's.docx");
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}
Added validations for the opened files.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const char * csInputFileNane="Users/bryanmichaelnorris/documents/extra credit assignment.docx";
ifstream infile(csInputFileNane);
if (!infile.is_open()) {
cerr << "Cannot open file \""<<csInputFileNane<<'"'<<endl;
return -1;
}
string line;
int numks = 0;
while (getline(infile,line))
{ int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k')
{
numks++;
}
x++;
}
}
infile.close();
const char *csOutFileName="number of k's.docx";
ofstream outfile(csOutFileName);
if (!outfile.is_open()) {
cerr << "Cannot open file \""<<csOutFileName<<'"'<<endl;
return -1;
}
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}
My goal is to take the text from "filename" that I have in my main directory, take the odd lines and send them over the filenameA, and the even lines to filenameB. From there, I want to splice them back into a new file. How can I create a while loop to do so?
// This program splits a file into two files from main directory
// and then splices the original file with a new name.
#include<iostream>
#include<fstream>
using namespace std;
void pause();
int main()
{
char filename[] = "Lab2Test.txt";
char filenameA[] = "LabTest-FA.txt";
char filenameB[] = "LabTest-FB.txt";
ifstream origin(filename);
ofstream fA(filenameA);
ofstream fB(filenameB);
if (! origin)
{
cout << filename << " could not be opened." << endl;
return -1;
}
string s;
int i=0;
while(getline(origin, s))
{
if(i % 2 == 1) //odd - write to LabTest-FA
fA << s << endl;
else
fB << s << endl;
i++;
}
}
void pause()
{
cin.sync();
cout << "Press any key to continue..." << endl;
cin.ignore();
}
First pick a book on C++ and learn a bit more about the language, you have lots of mistakes in the code.
Here is a working program, the best I can come up with.
// This program splits a file into two files from main directory
// and then splices the original file with a new name.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void pause()
{
cin.sync();
cout << "Press any key to continue..." << endl;
cin.ignore();
}
int main()
{
char filename[] = "Lab2Test.txt";
char filenameA[] = "LabTest-FA.txt";
char filenameB[] = "LabTest-FB.txt";
char filenew[] = "Lab2Test2.txt";
ifstream origin(filename);
fstream fA(filenameA, std::fstream::in | std::fstream::out | std::fstream::trunc);
fstream fB(filenameB, std::fstream::in | std::fstream::out | std::fstream::trunc);
ofstream fnew(filenew);
if (!origin)
{
cout << filename << " could not be opened." << endl;
return -1;
}
string s;
int i = 0;
while( getline(origin, s) )
{
if(i % 2 == 1) // odd - write to LabTest-FA
fA << s << endl;
else // even - write to LabTest-FB
fB << s << endl;
i++;
}
fA.flush(); // write to disk
fB.flush();
fA.seekg(0, ios::beg); // rewind the files to the beginning
fB.seekg(0, ios::beg);
string s1, s2;
while( getline(fB,s1) )
{
fnew << s1 << endl;
if(getline(fA,s2))
fnew << s2 << endl;
}
pause();
}