c++: Using a loop to open files - c++

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.

Related

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

How to check if csv file has no data?

I am reading data from a comma delimited csv file. I would like to verify that the file has data before reading and return an error if the file doesn't have any data.
const char* sample_data_file = "sample_data1.csv" ;
std::ifstream file(sample_data_file);
Thanks!
A simple call to stat will tell you if the file is empty. That should be enough to solve your problem.
check the size of the file when you open it?
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
ifstream myfile ("C:/temp/sample1.csv");
// this gives you the number of bytes in the file.
if (myfile.is_open())
{
long begin, end;
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
if(end-begin == 0)
{
cout << "file is empty \n";
}
else
{
cout << "size: " << (end-begin) << " bytes." << endl;
}
myfile.close();
}
else cout << "Unable to open file \n";
return 0;
}

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

Passing a file into a function

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

When compiling code antivirus says it's virus and delete it

Hi i try to make code in c++. This code only makes text file easy encrypted and save into a new file. And when i compile this code antivirus says, it is virus/spyware Gen:Variant.Kazy.20825. I dont know why it is virus.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void controlParameters(int argc){ //check if input parameters are ok
if(argc == 1){
cout << "Pokud chcete text zasifrovat, spustte program s parametrem: -enc \"Nazev_souboru.txt\"\n";
cout << "Pokud ho chcete desifrovat, spustte program s parametrem: -dec \"Nazev_souboru.txt\"\n";
}else if(argc > 3){
cout << "Moc parametru. Spustte si program bez parametru.\n";
}else if(argc < 3){
cout << "Chybi jeden parametr. Spustte si program bez parametru.\n";
}else{
cout << "Vsechno vypada zatim dobre\n";
}
}
void encryption(string &file); //encrypt text file
void decryption(string &file); //decrypt text file
bool controlFile(string &file); //check if file can be opened
int main(int argc, char **argv){
controlParameters(argc);
string file;
file = argv[2];
if(controlFile(file)){
}else{
cout << "Soubor nesel nacist." << endl;
return -1;
}
cout << "Ukonceno.\nZmacknete ENTER pro pokracovani..."<<endl;
cin.get();
return 0;
}
bool controlFile(string &file){
ifstream ifs;
ifs.open(file);
if(ifs.is_open()){
ifs.close();
return true;
}else{
ifs.close();
return false;
}
}
void encryption(string &file){
ifstream ifs;
ofstream ofs;
string line;
ifs.open(file);
ofs.open("encrypt.txt");
if(ifs.is_open()){
while(!ifs.eof()){
getline(ifs,line);
int a = line.length();
int i = 0;
while(i < a){
ofs << ((char)(line[i]^100));
}
line.clear();
ofs << "\n";
}
}else{
cout << "Nelze nacist soubor" << endl;
}
}
void decryption(string &file){
ifstream ifs;
ofstream ofs;
string line;
ifs.open(file);
ofs.open("decrypt.txt");
if(ifs.is_open()){
while(!ifs.eof()){
getline(ifs,line);
int a =line.length();
int i = 0;
while(i < a){
ofs << ((char)(line[i]^100));
}
line.clear();
ofs << "\n";
}
}else{
cout << "Nelze nacist soubor" << endl;
}
}
It's good practice to exclude your source-control directories from virus scanners; they can cause performance and locking problems even if there are no false positives while performing source-control actions or compiling (I've seen it happen several times).
So if only to make your programming experience more reliable, disable the virus scanner on those directories.
You may still want to scan the final, released version of your executable to help avoid false positives: after all, even if it's not your fault the virus scanner chokes, it's not a good impression to leave behind on a user.
Antivirus software uses "heuristics" to determine what is a virus and what isn't. So it looks for patterns in the file that does things that it finds suspicious. I can't see anything directly wrong in your code, so I suspect it's a "false-positive". I personally don't like antivirus software, it causes more problems than it solves...
By the way, you could add the "output filename" to your encrypt/decrypt function, and make them one function! ;)