Passing a file into a function - c++

I'm trying to create a program that passes a file to a function. The function is supposed to detect how many lines are in my file. I don't think I'm passing the file correctly into my function, I've tried several different ways. Any help will be greatly appreciated.
#include <iostream>
#include <fstream>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_lines(ifstream file)
{
int cnt3;
string str;
while(getline(file, str))cnt3++;
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(ifstream file);
string file;
file = argv[1];
if(argc == 1)die("usage: mywc your_file"); //for some reason not working
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int a;
cout << "File was opened\n";
a = num_of_lines(file);
cout <<"Lines: " << a << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}

Two problems with the function. First, you should pass the stream by reference. Second, you just forgot to initialise your counter.
int num_of_lines( ifstream &file )
{
int cnt3 = 0;
string str;
while( getline(file, str) ) cnt3++;
return cnt3;
}
The other thing is you're passing file to it (which is a string) instead of ifs. Change the call to:
a = num_of_lines( ifs );

Related

How to read lines from a file as well as from std::cin?

I'm writing a program, which takes the lines of text to work with from the file, the name of which the user passes as an argument, e.g. program <name of the file>. But if the name is not provided, the input is taken dynamically from std::cin. What I've tried:
Redirecting the buffer (somewhy causes segfault)
if (argc == 2) {
std::ifstream ifs(argv[1]);
if (!ifs)
std::cerr << "couldn't open " << argv[1] << " for reading" << '\n';
std::cin.rdbuf(ifs.rdbuf());
}
for (;;) {
std::string line;
if (!std::getline(std::cin, line)) // Here the segfault happens
break;
Creating a variable, in which the input source is stored
std::ifstream ifs;
if (argc == 2) {
ifs.open(argv[1]);
if (!ifs)
std::cerr << "couldn't open " << argv[1] << " for reading" << '\n';
} else
ifs = std::cin; // Doesn't work because of the different types
for (;;) {
std::string line;
if (!std::getline(ifs, line))
break;
Now I'm thinking of doing something with file structures/descriptors. What to do?
UPD: I would like to have the possibility to update the input source in the main loop of the program (see below).
The seg fault in your first example is due to a dangling pointer; right after you call std::cin.rdbuf(ifs.rdbuf()), ifs is destroyed.
You should do what #NathanOliver suggests and write a function which takes an istream&:
#include <iostream>
#include <fstream>
#include <string>
void foo(std::istream& stream) {
std::string line;
while (std::getline(stream, line)) {
// do work
}
}
int main(int argc, char* argv[]) {
if (argc == 2) {
std::ifstream file(argv[1]);
foo(file);
} else {
foo(std::cin);
}
}

Problem with getting text from a .txt file in c++ using fstream

And thisI am trying to get the things written in a .txt file called CodeHere.txt and here is my main.cpp:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
string lines[100];
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
lines[0] = line;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
cout << lines[0];
myfile.close();
return 0;
}
And the output is: Writing this to a file.Program ended with exit code: 0
But in my CodeHere.txt it has: hello
I tried saving it, but the result didn't change. I'm not sure whats going on. Can anyone help?
Are you sure that your .txt file is in the same repertory? To me, it just looks like you entered the path wrong. Try with the absolute path (full one). Another option is that you haven't saved the text file yet, you're just editing it, and so it is in fact empty, that would be why your cout doesn't print anything.
This should work, using a vector<string> to store the lines read from file
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
vector<string> lines;
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline(myfile, line) )
{
lines.push_back(line);
i++;
}
myfile.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << lines[0] << '\n';
return 0;
}
Try this:
vector<string> lines;
if (file.is_open()) {
// read all lines from the file
std::string line;
while (getline(file, line)) {
lines.emplace_back(line);
}
file.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << "file has " << lines.size() << " lines." << endl;
for (auto l : lines) {
cout << l << endl;
}

c++: Using a loop to open files

I have a vector of strings of 2 folder names vector <myClass> vec_fileNames; which I filled by reading from a fileNames.txt which contains 2 lines:
First
Second
ifstream inFile("c:/file names.txt");
if(!inFile)
{
cout << "File Not Found!\n";
inFile.close();
}
else
{
string line;
myClass class;
while (getline(inFile, line))
{
class.setFileName(line);
vec_fileNames.push_back(class);
}
So, at this point my vec_fileName[0].getFileName = First and vec_fileName[1].getFileName = second
Now I wanted to open files inside the folders who's names are in the vector in a loop so I did this:
for(int i = 0; i < vec_fileNames.size(); i++)
{
string fileName = vec_fileNames[i].getFileName();
ifstream inFile("C:/Program Folder\\" + fileName + "goalFile.txt");
if(!inFile)
{
cout << "File Not Found!\n";
inFile.close();
}
else
{
while (getline(inFile, line))
{
//do something
}
}
So far everything is good except for the file not being opened. Is this even something that can be done in c++ or is there an error in the way I'm opening the file?
I created the same folder structure as you have:
C:\
Program Folder
First
goalFile.txt
Second
goalFile.txt
And ran the following simple code. Node that I don't store the filenames in a class, but directly into a vector.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std; // I'm no fan of this, but you obviously used it.
void loadFileNames(vector<string>& vec_fileNames)
{
ifstream inFile("c:\\file names.txt");
if(!inFile.is_open())
{
cout << "File Not Found!\n";
return;
// inFile.close(); -- no need to close, it is not open!
}
else
{
string line;
while (getline(inFile, line))
{
cout << line << endl;
vec_fileNames.push_back(line);
}
}
}
void openFiles(vector<string>& vec_fileNames)
{
for(int i = 0; i < vec_fileNames.size(); i++)
{
string fileName = vec_fileNames[i];
string path("C:\\Program Folder\\" + fileName + "\\goalFile.txt");
ifstream inFile(path.c_str());
if(!inFile.is_open())
{
cout << "File" << vec_fileNames[i] << "Not Found!" << endl;
}
else
{
cout << "opened file in folder " << vec_fileNames[i] << endl << endl;
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
cout << endl;
}
}
}
int main(int argc, char* argv[])
{
vector<string> fileNames;
loadFileNames(fileNames);
openFiles(fileNames);
return 0;
}
That works, and produces the output:
First
Second
opened file in folder First
First goal file 1
First goal file 2
opened file in folder Second
Second goalfile 1
Second goalfile 2
The lines First goal file 1, etc. are the contents of the two files.

How to append to one file, then copy said file into another file

I feel like I've tried everything, I can get the first file to append to the second but cannot get the second file into a third. What am I doing wrong?
To be clear I need to take one file, append it to a second file, then put the contents of that second file into a third. I was able to simulate this outcome by putting both files into strings and then putting those strings into a third file, but that's not 'correct' in this problem.
I'm not particular to any way or any technique, I've tried a few and nothing works. This is the latest attempt, still doesn't work for the last step.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string a,b,c;
cout << "Enter 3 file names: ";
cin >> a >> b >> c;
fstream inf;
ifstream two;
fstream outf;
string content = "";
string line = "";
int i;
string ch;
inf.open(a, ios::in | ios:: out | ios::app);
two.open(b);
outf.open(c, ios::in);
//check for errors
if (!inf)
{
cerr << "Error opening file" << endl;
exit(1);
}
if (!two)
{
cerr << "Error opening file" << endl;
exit(1);
}
if (!outf)
{
cerr << "Error opening file" << endl;
exit(1);
}
for(i=0; two.eof() != true; i++)
content += two.get();
i--;
content.erase(content.end()-1);
two.close();
inf << content;
inf.clear();
inf.swap(outf);
outf.close();
inf.close();
return 0;
Here's an idea:
#include <fstream>
using namespace std;
void appendf( const char* d, const char* s )
{
ofstream os( d, ios::app );
if ( ! os )
throw "could not open destination";
ifstream is( s );
if ( ! is )
throw "could not open source";
os << is.rdbuf();
}
int main()
{
try
{
appendf( "out.txt", "1.txt" );
return 0;
}
catch ( const char* x )
{
cout << x;
return -1;
}
}

How do I print the content of a file?

How can I print the contents of a file, the name of which is specified via my program's command line?
I do not know how to give the name of file by command line and how to work with it.
For ex this is does not work:
int main(int argc, char *argv[])
{
FILE *f;
char s[20];
cin >> s;
f=fopen_s(s,"rt");
std::cout << f;
_getch();
return 0;
}
error C2660
#include <iostream>
#include <fstream>
int main(int argc , char *argv[])
{
if(argc < 2)
{
std::cout << " Wrong usage " << std::endl;
exit(0);
}
std::string file_name = argv[1];
std::ifstream fs;
fs.open(file_name.c_str());
std::cout << file_name << std::endl;
std::string line ;
while(fs >> line)
{
std::cout << line << std::endl;
}
return 0;
}
You cannot use << operator with char[]
Solution : You can use std::string
std::string s;
Use the string's c_str() value as name in fopen_s(name, "rt")
Solution : You need to put the file in the same directory as the executable
f = fopen_s(s.c_str(), "rt");
You cannot cout << FILE *f
Solution : read file content line by line as you print each line
char* line; //used to receive data for each line
int length; //used to represent how many characters have received
while ((getline(&line, &length, f) != -1) {
print("%s", line);
}