can't open file ,mystate for datafile2 =2 - c++

When I debug this I can see it opens datafile1 , it reads the firstline and
in the logfile I get roma-3-4.log
It change to c:/temp/roma-3-4.log but when I want to open it , it fails. I have check that the _Mystate = 2 .
What is the meaning of that
Thanks
in the transfersubs.cfg there is this
roma-3-4.log
** In the directory c:/temp/ I have the following file
roma-3-4.log
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
string logfile;
string errorfile;
short logfilesize1;
fstream dataFile1("c:/temp/transfersubs.cfg", ios::in);
if (dataFile1)
{
getline(dataFile1, input, '$');
logfile=input;
logfilesize1=input.size();
errorfile=input;
errorfile[logfilesize1-4]='e';
errorfile[logfilesize1-3]='r';
errorfile[logfilesize1-2]='r';
logfile="C:/Temp/"+logfile;
fstream dataFile2( logfile, ios::in);
if (dataFile2)
{
dataFile2.close();
}
else
{
cout << "ERROR: Cannot open logfile.\n";
}
dataFile1.close();
}
else
{
cout << "ERROR: Cannot open file.\n";
}
system("Pause");
return 0;
}

I believe your getline doesn't bother looking the newline but only for a $. You didn't post the file you are reading from, but check to ensure it has a $ at the end of the file name otherwise it will fetch the entire file.

It appears that unless you put a \n or endl after writing to the file using ofstream, ifstream won't be able to read anything from the file. In fact, adding a space after whatever you've written into file won't help either.
So always add a newline right after whatever it is that you've written to file using ofstream.

Related

In C++, opening a csv file with ifstream

I am trying to open a csv file in C++ using ifstream with a directory in the file path name. The file does reside in the specified directory location, but I observe an for the variable inFile when executing the code. My research up to this point says the code is correct, but something obviously is wrong. Any suggestions?
Thanks,
KG
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open("csvFile", ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
I found the answer to my csv file opening problem, a colleague assisted.
#David - You suggested removing the double quotes in the "inFile.open" line of code. In addition to removing the double quotes, I also needed to add c_str(), which "returns a pointer to a null-terminated character array with data equivalent to those stored in the string," .data() also performs the same function (cppreference.com).
#user4581301 - I am also aware that ios::in is implied with a ifstream, only included it here as a reference; thanks.
The modified code is listed below:
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open(csvFile.c_str(), ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
Really appreciate all the help.
Enjoy,
KG
Is this what you're trying to do?
#include <iostream> // std::{ cout, endl }
#include <string> // std::{ string, getline }
#include <fstream> // std::ifstream
auto main() -> int {
// Just to demonstrate.
// You want to use your real path instead of example.cpp
auto file = std::ifstream("example.cpp");
auto line = std::string();
while ( std::getline(file, line) )
std::cout << line << '\n';
std::endl(std::cout);
}
Live example

Why isn't my input stream opening my file? C++

I'm reading in a file name from the keyboard and opening the specified file. However it is not meeting my if statement that determines if it's open or not. Heres my code:
#include "prog.hh"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string fileName;
cout << "Enter the file name to be read: ";
cin >> fileName;
ifstream input_file("fileName");
std::string line_; // string which text file contents will be stored in
if(input_file.is_open()){ // validation to see if the file is open
while(getline(input_file, line_)){
std::cout<<line_<< '\n'; //prints the contents of the file into the console
}
input_file.close();
}
else {
std::cout<<"File is not open"<< '\n';
}
std::cin.get();
After being compiled, I type in the file name I want to open and I get back the else message "File is not open", although the ifstream should of opened it. I definitely have the right file I'm trying to open in the correct folder. Any help appreciated, thanks.
change
ifstream input_file("fileName");
to
ifstream input_file(fileName);

Simple File-I/O Program C++

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
The above code is supposed to read from the file "data.txt" the following text
"The default behaviour of ifstream type stream (upon opening files ) allows users
to read contents from the file. if the file mode is ios::in only then reading is
performed on a text file and if the file mode also includes ios::binary along with
ios::in then, reading is performed in binary mode. No transformation of characters
takes place in binary mode whereas specific transformations take place in text mode."
and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).
Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.
Can someone tell me what's going on in here ?
If any one of the attempted reads in the file is longer than 74 characters, getline will set the failbit for fin, and you will never reach the end of the file. Change your code to the following:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
This will break your loop if you reach the end of the file or if something catastrophic happens to the stream. You'll also need to think about handling the extra read that is performed if the file ends with a period.
Consider switching to std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}

C++ file won't open

I'm new to C++ and am trying to open a file, but can't get it to work. The file is definitely there, in the same directory. I have tried unhiding extensions (it's definitely called test.txt and not test.txt.txt for example), and also tried using the full path. The file is not open anywhere. Any ideas (I'm sure it's something simple but I'm stuck)?
string mostCommon(string fileName)
{
string common = "default";
ifstream inFile;
//inFile.open(fileName.c_str());
inFile.open("test.txt");
if (!inFile.fail())
{
cout << "file opened ok" << endl;
}
inFile.close();
return common;
}
If you specify inFile.open("test.txt") it will try to open "test.txt" in the current working directory. Check to make certain that is actually where the file is. If you use absolute or relative pathing, make sure that you use '/' or '\\' as the path separator.
Here is an example that works when a file exists:
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
bool process_file(string fileName)
{
ifstream inFile(fileName.c_str());
if (!inFile)
return false;
//! Do whatever...
return true;
}
int main()
{
//! be sure to use / or \\ for directory separators.
bool opened = process_file("g:/test.dat");
assert(opened);
}

Visual C++ - Cannot open text file

Simple program to open up a file and read it's contents. Then a test at the end to see if I did in fact get the information. Every time I run it it tells me that it cannot open the file. I will post the contents of SaleSlips below. Why isn't it opening the file? It is also attempting to delete the file every run as well.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct SaleSlip{
char name[20];
int prodID;
double value;
};
void main(){
fstream slips;
SaleSlip sales[17];
slips.open("SaleSlips.txt", ios::in);
if(slips.eof()){
cout << "Cannot open file - SaleSlips.txt"<< endl;
system("pause");
exit(2);
}
int i = 0;
while(!slips.eof()){
slips.getline(sales[i].name, ' ');
slips >> sales[i].prodID;
slips.ignore(5, ' ');
slips >> sales[i].value;
slips.ignore(80, ' ');
i++;
}
cout << sales[1].value;
slips.close();
system("pause");
}
Eric 1 200000.00
Sookie 2 200.00
Sookie 4 200.50
You're opening the stream in output mode by using ios::out. Use ios::in to read from it.
You've got a lot of other issues, too. IE:
-The if(!slips.eof()) after the file open will always cause an exit unless the file is empty.
-In your while loop, you are (probably accidentally) attempting to write the prodID and value into the slips file using <<. Use >> to read from a stream and << to write to it.
You have two problems:
You're opening the file for output (writing)
slips.open("SaleSlips.txt", ios::out);
Useios::in instead for input (reading)
slips.open("SaleSlips.txt", ios::in);
Next, you're immediately testing for !eof(), which is the wrong logic.
if(!slips.eof())
You don't want to be at eof() when opening the file for input. eof() is end of file. When first opening the file for input you want to be at the beginning of the file; being at eof() is a bad thing. Your code should error out if eof() is true, not if it's false:
if(slips.eof()) {
// It's an error if we're starting at eof()
}