File won't open, I don't know why - c++

My FILE WONT OPEN HELP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input_file_name, output_file_name; //file names
ifstream infile; //input file object
ofstream outfile; //output file object
//prompt user for input file
cout << "Enter the input file name: ";
cin >> input_file_name;
//open input file
infile.open(input_file_name.c_str());
//check if file opened successfully
if (!infile)
{
cout << "Error: Unable to open file" << endl;
cout << "Terminating program...";
return 1;
}
else
{
cout << "Successfully opened file!";
}
return 0;
}
when asked for user input i type filename.txt and it wont display successfuly opened message? why....i have the filename.txt on my pc

First off, pardon my use of 'goto', I just felt like it... Try something like what I have shown below where I check if the file actually opened (save the code stub as "asdf.cpp"). Of course you will have to read the data into an array, but it may be a good place to start.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
string line;
ifstream f("asdf.cpp");
if ( !f.is_open() )
goto error_file_not_open;
while( getline(f, line) )
cout << line << endl;
f.close();
return 0;
error_file_not_open:
cout << "Could not open file" << endl;
return -1;
}

If you want to save and read values from/to file, then try something like this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
// Write values to a file
const int size = 5;
int values[] = { 1,2,3,4,5,6 };
ofstream myfile("lol.txt");
if (myfile.is_open())
{
for (int count = 0; count < size; count++) {
myfile << values[count] << endl;
}
myfile.close();
}
else {
cout << "Unable to open file";
}
// Write read values from a file
std::ifstream file("lol.txt");
if (file.is_open()) {
std::string line;
while (getline(file, line)) {
cout << line.c_str() << endl;
}
file.close();
}
else {
cout << "Unable to open file";
}
}

I'am afraid that your file is not an ANSI-ASCII encoded text file. May be it is encoded by UTF-8 or the Unicode format. The following code will check that the encode of your file. Just try to run it or you could open the lol.txt by any text editor such as, vscode or notepad++.
It will show the encode format of the file at the right-down corner.
Another way to prevent from this issue is try to save the text file to the ANSC-ASCII format. Hope this will help! ^_^
#include <iostream>
#include <fstream>
using namespace std;
unsigned char UTF8Header[] = {0xef, 0xbb, 0xbf};
unsigned char UNICODEHeader[] = {0xff, 0xfe};
int main()
{
char fileName[] = "lol.txt"; // replace the file with your actual file name.
std::ifstream in;
char buffer[3] = {0};
in.open(fileName, std::ios::in | std::ios::binary);
if (!in.is_open())
{
std::cout << "Error opening file";
return -1;
}
if (!in.eof())
in.read(buffer, 2);
if (!in.eof())
in.read(buffer + 2, 1);
if (buffer[0] == UNICODEHeader[0] && buffer[1] == UNICODEHeader[1])
cout << "The file is encoded by unicode format" << endl;
else if (buffer[0] == UTF8Header[0] && buffer[1] == UTF8Header[1] && buffer[2] == UTF8Header[2])
cout << "The file is encoded by UTF-8 format" << endl;
return 0;
}

Related

fstring not reading from .txt file

I am trying to write a program that will read a .txt file that is called when the program is run from terminal.
the command used will be;
$ ./myexecutable input.txt
My program and the input.txt are in the same directory. My code so far is as follows
#include <string>
#include <fstream>
using namespace std;
int main(int argc , char* argv[]){
string temp = "here";
string filename = argv[1];
ifstream myFile (filename);
myFile.open(filename);
if (myFile.is_open()){
while (getline (myFile, temp)){
cout << temp << endl;
myFile.close();
}
} else {
cout <<< "You have Entered Wrong File Name" << endl;
}
cout << "do with the simple program" << endl;
return 1;
};
but the output I get is just
file opened, do with the simple program
I am not really familiar with fstream so don't know where I may have gone wrong. I followed their tutorial found here.
but clearly I've done something wrong.
Thanks for your help.
This is the corrected code!!
You were opening myFile twice!!
First time in this statement ifstream myFile (filename);
Second time in this statement-myFile.open(filename);
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc , char* argv[]){
string temp = "here";
string filename = argv[1];
ifstream myFile (filename);
if (myFile.is_open()){
while (getline (myFile, temp)){
cout << temp << endl;
myFile.close();
}
} else {
cout << "You have Entered Wrong File Name" << endl;
}
cout << "do with the simple program" << endl;
return 1;
};

Input/Output operations on characters

I'm learning file handling in C++. I was implementing the exact same code in my Code::Blocks 20.03 as given in one of the programs of the book, but it's displaying no output after line 26, i.e.
cout<<"\nReading the file contents: ";
I've figured maybe these lines are erraneous, but I can't debug how:
while(file){
file.get(ch);
cout<<ch;
}
Here is the full code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int main()
{
char String[80];
cout<<"Enter a string: ";
cin>>String;
int len = strlen(String);
fstream file;
cout<<"Opening the 'TEXT' file and storing the string in it.\n\n";
file.open("TEXT",ios::in|ios::out);
for(int i=0;i<len;i++)
file.put(String[i]);
file.seekg(0);
char ch;
cout<<"\nReading the file contents: ";
while(file){
file.get(ch);
cout<<ch;
}
file.close();
return 0;
}
The openmode
ios::in | ios::out
will not create a new file if "TEXT" does not exist, but result in an error. Most likely this file does not exist, so you get an error and any subsequent input and output operations on the stream are ignored. You could use
ios::in | ios::out | ios::trunc
to destroy the contents of an existing file or create a new one if the file does not exist.
For further information please consult the table on https://en.cppreference.com/w/cpp/io/basic_filebuf/open where all the different combinations of openmode are detailed.
Lastly, it's always good practice to check if the file was opened:
if(!file) { /* error */ }
You can use is_open() to check if the file was successfully opened and then use an if else loop that will validate if the file can't be found. You don't need to use ios::in|ios::out.
Here's an example that should work:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream filestr;
filestr.open ("test.txt");
if (filestr.is_open())
{
filestr << "File successfully open";
filestr.close();
}
else
{
cout << "Error opening file";
}
return 0;
}
You need to check for end of file inside the loop.
while(file) {
file.get(ch);
if(ch == -1) break;
cout << ch;
}
Also, try opening the file in write mode first and then close it and open it in read mode.
cout << "Opening the 'TEXT' file and storing the string in it.\n\n";
ofstream outfile("TEXT");
if(outfile.is_open()) {
for(int i = 0; i < len; i++)
outfile.put(String[i]);
outfile.close();
}
ifstream infile("TEXT");
char ch;
if(infile.is_open()) {
cout << "\nReading the file contents: ";
while(infile) {
file.get(ch);
if(ch == -1) break;
cout << ch;
}
infile.close();
}

C++ copying another file

i was wondering how to use c++ ifstream/ofstream to copy a file and save it as another name.
this is as far as i got. I know how to get the file, its just that i don't know how to copy that file and save it as a different name.
#include<iostream>
#include<fstream>
#include<string>
namespace std;
int main()
{
ofstream
ifstream
cout << "enter your file you want to copy"<< endl;
cin >> input_file_name;
in_file.open(input_file_name);
if (!in_file)
{
cout <<" there is no such file"<<endl;
return 0;
}
cout <<" enter the name you want to save this copy file"<<endl;
cin >> output_file_name;
out_file.open(output_file_name);
if (!out.file)
{
cout<<"file is not available"<<endl;
return 0;
}
in_file.close();
out_file.close();
return 0;
}
rdbuf with overloaded << is standard way to go.
ifstream src;
ofstream dst;
src.open("from", ios::in | ios::binary);
dst.open("toto", ios::out | ios::binary);
dst << src.rdbuf();
src.close();
dst.close();
Copy a file and save it on another file:
#include <fstream>
#include <iostream>
#include <string>
int main(int arc, char* argv[]) {
std::ifstream file1(argv[1]);
std::ofstream file2(argv[2]);
std::string line;
if (file1.good() && file2.good()) {
while (getline(file1, line)) {
file2 << line;
file2 << '\n';
}
}
file1.close();
file2.close();
}
Basically you want to read a character at a time and write said character to the output stream. There's a get() overload which accepts a streambuf output variable that would work. You could also use the example on cplusplus.com rdbuf documentation.
http://www.cplusplus.com/reference/fstream/ofstream/rdbuf/
This code below should give you a sense of what you want to do.
There are few things you should keep in mind, for example:
is the path of the file giving to read is valid?
or do you want to save the data from an output file if that file exists, before pushing new data?.
You could test this code by just creating a file into your desktop or any location, just change the filePath and destinationPath variables then run the code. (c++ 11)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<string> readFromFile(const char *filePath) {
vector<string> container;
ifstream obj(filePath); // automatically our file would be open
if (obj.is_open()) { // we check anyways
string line = "";
while(getline(obj, line)) {
if (!line.empty()) // prevent us to insert empty line into our vector
container.push_back(line);
}
obj.close(); // close after we finish reading to avoid corruption
}
return container;
}
bool pipingToDestination(vector<string>data, const char *filePath) {
std::filebuf fb; fb.open(filePath,std::ios::out); // open the file
ostream obj(&fb);
if (!data.empty() && fb.is_open()) { // make sure we have some data && the file file is open to write
for (string x: data) { // c++11
obj << x << endl;
}
fb.close();
return true;
}
return false;
}
int main() {
string filePath = "/Users/lamar/Desktop/testFile.txt";
vector<string> data = readFromFile(filePath.c_str());
cout << "File has passed data into container ... \n";
for(string x: data) {
cout << x << endl;
}
cout << "Creating destination file \n";
string destinationPath = "/Users/lamar/Desktop/destFile.txt";
cout << "has piped data into file " << boolalpha << pipingToDestination(data, destinationPath.c_str());
return 0;
}
This is not the only way to do this, but this code should put you on a direction

Line and word counter function not adding up correctly C++

This program is supposed to tell the user how many words and lines are in their program (text file only). The two functions that I have written both work, except the num_of_lines function is counting one more line than is correct every time and the num_of_words function is off by about 300 words every time. Not sure what I am doing wrong here. Any help will be greatly appreciated, thanks. I copy and pasted an output after my code and compared it to wc.
#include <iostream>
#include <fstream>
#include <cctype>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_words(string name)
{
int cnt2 = 0;
ifstream iwords;
iwords.open(name);
string w;
if(iwords.is_open())
{
while(iwords >> w)
{
cnt2++;
}
}
else cerr <<"can not open" + name << endl;
iwords.close();
return(cnt2);
}
int num_of_lines(string name)
{
int cnt3 = 0;
string line;
ifstream ilines;
ilines.open(name);
if(ilines.is_open())
{
while(getline(ilines, line))
{
cnt3++;
}
}
else cerr <<"can not open" + name << endl;
ilines.close();
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(string name);
if(argc == 1)die("usage: mywc your_file");
string file;
file = argv[1];
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int b;
b = num_of_words(file);
cout <<"Words: " << b << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Zacharys-MBP:c++ Zstow$ my sample.txt
Chars: 59526
Words: 1689
Lines: 762
Zacharys-MBP:c++ Zstow$ wc sample.txt
761 2720 59526 sample.txt
Zacharys-MBP:c++ Zstow$
Most files (especially programs) will end in a new line. You may not see this in your editor but it is probably there. You will have to check the last line to see if it actually contains any content, or if it is empty.
The istream operator (>>) will detect any group of characters between whitespace to be a "word." So if you're parsing programs, you may have:
for(int i=1; i<73; i++)
The istream operator will see 4 words: [for(int, i=1;, i<73;, i++)]

C++ How do i add a string to an existing text file without overwriting it?

I have coded a programm which can load one text file, can decide how long each word is and can write txt files based on the length of the words. But when i run the programm, the new text files are always filled with just one word(each new word with an already existing text file for his length just overrides the text file)
The start text file looks like this():
http://i.stack.imgur.com/WBaRf.png
My new created text files(named after their length for example: 7.txt) after i runned the programm:
http://i.stack.imgur.com/6QKgE.png
My code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
char filename[128];
ifstream file;
char line[100];
cout << "Input filename: " << flush;
cin.getline(filename, 127);
file.open(filename, ios::in);
if (file.good())
{
file.seekg(0L, ios::beg);
int number = 0;
while (!file.eof())
{
file.getline(line, 100);
stringstream stream;
stream << line;
number++;
cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
std::stringstream sstm;
int laenge = stream.str().length();
string txt = ".txt";
sstm << laenge << txt;
string result = sstm.str();
std::ofstream outFile(result);
outFile << line << endl;
outFile.close();
}
}
else
{
cout << "File not found" << endl;
}
while (true)
{
};
return 0;
}
My goal is that i have sorted the whole words into the file their files, the only problem is that they overwrite themself... How can i get rid off that?
If you don't want to overwrite the content of the file, you can open the file and specify that you want to append to the file:
std::ofstream outFile(result, ios::app);
// ^^^^^^^^