writing to multiple files at a time - c++

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

Related

Read Multiple Files In C++

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.

Behaviour of static ifstream object inside a function

I've made a static ifstream object inside a function and I'm associating it with the file given in the function argument.
In the main function, I'm calling this function twice, each time with a different file name.
Here's my code:
#include <iostream>
#include<fstream>
using namespace std;
void print_file(string path)
{
static ifstream ifs{path.c_str()};
if (ifs.is_open())
{
cout<<endl<<"Going to print the file: "<<endl;
char c = ifs.get();
while (ifs.good()) {
std::cout << c;
c = ifs.get();
}
}
else
cout<<endl<<"File couldn't be opened"<<endl;
}
int main(int argc, char**argv)
{
if(argc!=3)
{
cout<<endl<<argv[0]<<" file_name1 file_name2"<<endl;
return 0;
}
print_file(argv[1]);
print_file(argv[2]);
}
Given below is the output:
[vishal1#localhost temp]$ ./exe file1.txt file2.txt
Going to print the file:
File 1 contents
Going to print the file:
Due to some reasons file1 is not getting printed the second time. What's the reason?
The reason is that in the first call you read all the contents of the file, but you're not resetting the read file pointer to the beginning. So the next call the file status is still and the end of the file and ifs.good() returns false.
You need to "rewind" the file, and clear the status flags.
Also note that you should never use eof() in a loop condition, and using good() is just the same.
In your case, use e.g.
while (ifs.get(c))
{
std::cout << c;
}
instead.

How to read from an input stream into a file stream?

I am trying to bind input stream with a file stream , I hope that input something from input stream and then automatic flush to the file stream
It does not work...I enter something from keyboard , outfile is still empty
#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outfile("outfile" , ofstream::app | ofstream::out);
if(!outfile)
throw runtime_error("Open the file error");
ostream * old_tie = cin.tie();//get old tie
cin.tie(0);//unbind from old tie
cin.tie(&outfile);//bind new ostream
string temp;
while(cin >> temp)
{
if(temp == ".")//stop input
break;
}
cin.tie(0);
cin.tie(old_tie);// recovery old tie
return 0;
}
Your program is too complicated and is misusing tie(). Try the following:
#include <iostream>
#include <fstream>
int main() {
using namespace std;
ofstream outfile("outfile" , ofstream::app | ofstream::out);
if(!outfile) {
cerr << "Open the file error";
return 1;
}
char data(0);
while(data != '.') {
cin.get(data);
cin.clear(); // Prevents EOF errors;
outfile << data;
}
return 0;
}
It reads char by char until it finds a .
Errors:
why make throw exception if you don't catch it...
close file please
do you put data from file to temp and go through it to find "." and
end program?
Why do you use pointer for old_tie use it for the first ofstream file
like this ofstream * file.
fix if statement and break
include string library -- //This might solve your problem
what is filename??
is tie(0) function to unbind?
//EDIT
Explanation:
once you find first period with find_first_of function you create a substr and copy it into outfile. The Solution is so efficent and works every time. The logic is as simple as it can get. Don't use unnecessary functions and initialize unnecessary variables because it is more complex and more prone to errors when you have too many variables.
Solution: - No need for cin.tie()
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outfile("outfile" , ofstream::app | ofstream::out);
string s;
getline(cin, s);
int i = s.find_first_of(".");
if(i!=std::string::npos)
{
s = s.substr(0, i);
outfile << s;
}
else
{
cout << "No periods found" << endl;
}
}
Compiled code - http://ideone.com/ooj1ej
If this needs explanation please ask questions in comments below.

C++ File accessing/ input and output

I'am having a rather difficult time with this program (see code below). It is supposed to :
Create an array of 26 components to do the letter count for the 26 letters in the alphabet and a variable for the line count.
Create an ASCII (or text) file that contains text and will be used as input to my program.
Call that file "textinput" and then, have the output stored in a file called "textoutput".
Can anyone tell me what I'am doing wrong? I keep getting "File not found" errors.
#include <iostream>
#include <cstdio>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
int lineCount = 0;
int letterCount[26];
for(int i = 0; i < 26; i++)
letterCount[i] = 0;
ifstream infile;
infile.open("textinput.txt", ios::in);
if(!infile)
{
cerr<<"File does not exist."<<endl;
exit(1);
}
ofstream outfile;
outfile.open("textoutput.txt", ios::out|ios::binary);
if(!outfile)
{
cerr<<"File cannot be opened."<<endl;
exit(1);
}
char data[100];
outfile<<data;
while(infile>>data)
{
outfile<<data<<endl;
}
while(infile)
{
char ch1 = infile.get();
if(ch1 == '\n')
{
lineCount++;
continue;
}
int asciiNum = (int)ch1;
if(asciiNum > 96)
{
asciiNum = asciiNum - 97;
}
else
{
asciiNum = asciiNum - 65;
}
letterCount[asciiNum]++;
}
infile.close();
outfile.close();
system("PAUSE");
return 0;
}
The funny thing is, "File not found" errors are not possible with your program.1 So, I'm going out on a limb and suggest that you need to qualify the path to your executable!
Say, you compiled with something like
gcc program1.cpp -o program1
To execute, you must use
./program1
Because program1 won't work. The reason is that with 99% certainty, your current working directory is not in the search PATH for executables (and you want to keep it that way).
Beyond this, yes, do make sure that the textinput.txt exists in the same directory.
1(There's no such error message in the program. You should know: you programmed it!)
ifstream class is used to read from files and to read from files you must need to create it first which you haven't done, so first create the file .
By doing like this :
ifstream infile;
infile.open("textinput.txt", ios::in);
you are trying to read from a file which has not been created yet OR may be as described in other answer or the comments that your file doesn't exist in the same directory.
You better use ofstream to first write on the file and then use ifstream.
Does your code work if you have the file? If it does try removing the ios::out.If i'm not mistaken ios::out is used when you do not want to truncate your old content in the file,but that implies you already have it.

C++ open a file as read-only

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