I am trying to read two files "ListEmployees01.txt" and "ListEmployees02.table". But the program reads only the "ListEmployees01.txt" file and cout is just from that file.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
int main()
{
freopen("ListEmployees01.txt", "r", stdin);
string s;
while (getline(cin, s))
cout << s<<endl;
fclose(stdin);
freopen("ListEmployees02.table", "r", stdin);
while (getline(cin, s))
cout << s<<endl;
}
You can use std::ifstream instead of changing std::cin's behavior.
I would do the following using fstream
#include <fstream>
void readAndPrint(const char *filename) {
std::ifstream file(filename);
if (file.is_open()) {
std::string line;
while (getline(file, line)) {
printf("%s\n", line.c_str());
}
file.close();
}
}
int main() {
readAndPrint("ListEmployees01.txt");
readAndPrint("ListEmployees02.table");
return 0;
}
If you must use freopen, then have a look at man freopen, or the C++ reference http://www.cplusplus.com/reference/cstdio/freopen .
In your case , in the case of second file you are using the stdin which is already closed by below line , hence it is a dangling pointer after file close
fclose(stdin)
You can use fopen instead of freopen for the second file.
Please check the below paragraph from www.cplusplus.com/reference/cstdio/freopen/
If a new filename is specified, the function first attempts to close
any file already associated with stream (third parameter) and
disassociates it. Then, independently of whether that stream was
successfuly closed or not, freopen opens the file specified by
filename and associates it with the stream just as fopen would do
using the specified mode.
Related
I'm having some problems reading a string into an array. my file contains the following strings running horizontally down the page.
File:
dog
cat
rabbit
mouse
Code:
#include <string>
int i = 0;
using namespace std;
int main()
{
FILE * input1;
fopen_s(&input1, "C:\\Desktop\\test.dat", "r");
string test_string;
while (!feof(input1)) {
fscanf_s(input1, "%s", test_string);
i++;
}
return 0;
}
Any advice would be appreciated, Thanks!
You should use ifstream and std::getline
Now, I'm going to walk you through reading lines from the file using ifstream
Include fstream to use ifstream.
#include <fstream>
Opening a file:
To open a file, create an object of ifstream, and call it's method open and pass the filename as parameter. ifstream opens a file to read from it. (To write in a file, you can use ofstream)
ifstream fin;
fin.open("C:\\Desktop\\test.dat");
Or you can simply pass the filename to the constructor to create an object of ifstream and open a file.
ifstream fin("C:\\Desktop\\test.dat");
Reading from the file:
You can use stream extraction operator (>>) to read from the file, just like you use cin
int a;
fin >> a;
To read a line from a file using the above created fin (using a char array)
char arr[100];
fin.getline(arr, 100);
Better yet, you should use std::string instead or char arrays, using std::string, you can read a line using std::getline
string testString;
getline(fin, testString);
Now, let's change your code to use ifstream and getline
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
ifstream input1;
input1.open("C:\\Desktop\\test.dat");
string test_string;
while (getline(input1, test_string)) {
i++;
}
return 0;
}
I want to create multiple files inside a loop and write something into them. I have made the following code. But it only creates one file named '1' instead of five files (from 1 to 5):
#include <fstream>
#include<iostream>
using namespace std;
int main(){
FILE *fp;
ofstream os;
char i;
char fileName[] = "0.txt";
for(i='1';i<='5';i++)
{
fileName[0]=i;
.
os.open (fileName);
os<<"Hello"<<"\n";
}
}
Is there anything wrong in the code? How will I get the five files?
The reference for std::ofstream::open specifically states:
Open file Opens the file identified by argument filename, associating
it with the stream object, so that input/output operations are
performed on its content. Argument mode specifies the opening mode.
If the stream is already associated with a file (i.e., it is already
open), calling this function fails.
You never close the file you're working with in your loop so open for the second-fifth time fails.
add it:
for(i='1';i<='5';i++)
{
fileName[0]=i;
os.open (fileName);
os<<"Hello"<<"\n";
os.close();
}
Also, you should check if open() succeeded:
for(i='1';i<='5';i++)
{
fileName[0]=i;
os.open (fileName);
if(os) // checks if open() succeeeded
{
os<<"Hello"<<"\n";
os.close();
}
}
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream os;
char fileName[] = "0.txt";
for(int i = '1'; i <= '5'; i++)
{
fileName[0] = i;
os.open(fileName);
os << "Hello" << "\n";
os.close();
}
}
I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)
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.
I have written a program which opens a file then displays line by line its contents (text file)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
string STRING;
ifstream infile;
infile.open(argv[1]);
if (argc != 2)
{
cout << "ERROR.\n";
return 1;
}
if(infile.fail())
{
cout << "ERROR.\n";
return 1;
}
else
{
while(!infile.eof())
{
getline(infile,STRING);
cout<<STRING + "\n";
}
infile.close();
return 0;
}
}
What do I need to add to make the file be read only ?
(infile.open(argv[1]) is where am guessing something goes)
The class ifstream is for reading only so, problem solved. Also, did you really mean to check argc after using argv[1] ?
On the other hand, when you use fstream you need to specify how you want to open the file:
fstream f;
f.open("file", fstream::in | fstream::out); /* Read-write. */
The default mode parameter of open for ifstream class is ios::in. That is
infile.open(argv[1]);
is same as:
infile.open(argv[1], ios::in);
So you are opening the file in read-only mode.
You already open the file for read-only. Your can't write to it if you use ifstream. Even:
infile.rdbuf()->sputc('a');
is guaranteed to fail.
You don't need to do anything as the default value for the openmode is already ios_base::in. So you're already good to go :)
See here for more details: http://en.cppreference.com/w/cpp/io/basic_ifstream/open