ifstream ofstream on mac - c++

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;
}

Related

std::ofstream sometimes fails to open file in a 'for' loop

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?

How to write the result of a function to a file C++

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;
}

Reading lines from file in C++

Why can't I get each line in a file printed with this? It outputs nothing.
string line;
ifstream s {"book_list.txt"};
while (getline(s, line)) {
cout << line << endl;
}
I've included fstream, sstream, string, stdio.h, stdlib.h and am using namespace std;
#include<iostream>
#include<fstream>
#include<string>
using namespace std
int main()
{
string line;
ifstream s ("book_list.txt");
if (s.is_open())
{
while ( getline (s,line) )
{
cout << line << endl;
}
s.close(); // Don't forget to close the file
}
else
cout << "Unable to open file";
return 0;
}
I hop it helps.
I guess the file doesnt exist.
Please check with:
if(!s.good()) {
// error
}
or
while (s.good()) {
// process.
}
You should do something like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string sLine = "";
ifstream infile;
infile.open("temp.txt");
if(infile.is_open()){
while (getline(infile, sLine))
{
cout << sLine << endl;
}
}
infile.close();
cout << "Read file completed!!" << endl;
}
#include <iostream>
#include <fsstream>
using namespace std;
int main()
{
string data;
int counter = 0;
ifstream infile("test_file.txt");
while (!infile.eof()){
getline(infile , data);
counter += 1;
}
cout << "The number of lines is : " << counter << endl;
return 0;
}

ifstream::read not working?

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();
}

Checking if word exists in a text file c++

I need to check if a word exists in a dictionary text file, I think I could use strcmp, but I don't actually know how to get a line of text from the document. Here's my current code I'm stuck on.
#include "includes.h"
#include <string>
#include <fstream>
using namespace std;
bool CheckWord(char* str)
{
ifstream file("dictionary.txt");
while (getline(file,s)) {
if (false /* missing code */) {
return true;
}
}
return false;
}
std::string::find does the job.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool CheckWord(char* filename, char* search)
{
int offset;
string line;
ifstream Myfile;
Myfile.open (filename);
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile,line);
if ((offset = line.find(search, 0)) != string::npos)
{
cout << "found '" << search << "' in '" << line << "'" << endl;
Myfile.close();
return true;
}
else
{
cout << "Not found" << endl;
}
}
Myfile.close();
}
else
cout << "Unable to open this file." << endl;
return false;
}
int main ()
{
CheckWord("dictionary.txt", "need");
return 0;
}
char aWord[50];
while (file.good()) {
file>>aWord;
if (file.good() && strcmp(aWord, wordToFind) == 0) {
//found word
}
}
You need to read words with the input operator.