Reputation: 2721
Hi I am trying to read a file name from another file and then read it. But I can only read the first file which contains the name of the second file I want to open. Here is how I am doing it..
int main()
{
freopen("input1.txt","r",stdin);
while(cin>>fileName>>source>>destination)
{
//reads perfectly
char file[100];
for(int i=0;i<(int)fileName.size();i++)
file[i] = fileName[i];
file[(int)fileName.size()] = NULL;
freopen(file,"r",stdin);
mp.clear();
mp1.clear();
for(int i=0;i<cityNumber;i++)
adj[i].clear();
cityNumber = 0;
while(cin>>city1>>city2>>distanc)
{
//doesn't read
}
}
Upvotes: 1
Views: 944
Reputation: 171107
Your code uses overly complicated constructs. Why not just do it the straightforward C++ way:
#include <fstream>
int main()
{
std::ifstream input1("input1.txt");
while(input1 >> fileName >> source >> destination)
{
std::ifstream file(fileName.c_str());
mp.clear();
mp1.clear();
for(int i=0;i<cityNumber;i++)
adj[i].clear();
cityNumber = 0;
while(file >> city1 >> city2 >> distanc)
{
//work with values
}
}
Upvotes: 4
Reputation: 27365
A few things to consider:
do not use freopen/fopen family of files in C++ (unless it's a really special case)
do not mix std::iostreams with fopen family of files (freopen should not be used here)
these two points will fix your particular error (as @Angew pointed out)
prefer std::string
with std::getline
instead of char file[100];
This avoids buffer overflow if reading over 100 chars (I believe you don't check for errors) and simplifies your code.
prefer iterators over iterating by index.
That means instead of:
for(int i=0;i < cityNumber;i++)
adj[i].clear();
you could/should write:
// C++11
for(auto& city: adj)
city.clear();
// C++98
for(<type of adj>::iterator city = adj.begin(); city != adj.end(); ++city)
city->clear();
Upvotes: 1
Reputation: 183873
The man page for freopen
says:
The
freopen()
function opens the file whose name is the string pointed to bypath
and associates the stream pointed to by stream with it. The original stream (if it exists) is closed.
Hence,
freopen("input1.txt","r",stdin);
closes the stdin
stream, and
freopen(file,"r",stdin);
finds no open stream to associate to file
.
You should probably plain fopen
the file input.txt
and read from it to leave stdin
for the final target.
Upvotes: 1