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();
}
Related
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
string data;
file.open("newFile.txt", ios::out | ios::in);
if(!file){
cout<<"File open failed!"<<endl;
}else {
cout<<"File open success!"<<endl;
cout<<"Please enter the data to save into the file"<<endl;
getline(cin, data);
file << data;
string d;
file.seekp(0);
if(file.is_open()) {
while(1){
d = file.get();
cout<<d;
if(file.eof()){
break;
}
}
}
file.close();
}
return 0;
}
Forexample: I wrote (c++ is an interesting language). after it is successfully written to the file, again I wrote (I like it) and after that the file content becomes (I like it interesting languageĀ )
I am trying to run below code but it is neither showing any file on the path nor reading anything from it. Whatever I am writing into the file through "cin >>" it is not being written. Can anybody please let me know mistake in my code below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char string[80];
cout << "Enter Input" << endl;
cin >> string;
int len = strlen(string);
fstream file;
file.open("TEXT", ios::in | ios::out);
for (int i = 0; i < len; i++)
file.put(string[i]);
file.close();
file.open("TEXT", ios::in | ios::out);
file.seekg(0);
cout << "Output" << endl;
while (file) {
char ch;
file.get(ch);
cout << ch;
}
file.close();
return 0;
}
You should add the fstream::app flag in your open call and this will do the trick !
Don't mess with file modes you don't need (or understand). Open the file for writing only first, and then open it for reading only next. Use different streams for reading and writing.
ofstream file_out;
file_out.open("TEXT");
for (int i = 0; i < len; i++)
file_out.put(string[i]);
file_out.close();
ifstream file_in;
file_in.open("TEXT");
cout << "Output" << endl;
while (file_in) {
char ch;
file_in.get(ch);
cout << ch;
}
Unless you actually understand the rules concerning ios::in and ios::out it's safer to just use ifstream when you want input and ofstream when you want output.
More reading if you do want to understand the rules.
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;
}
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
I'm writing, reading and deleting the content of a file. Eeverything works fine except the delete part, as when I press y it says deleted but doesn't display any records.
typedef struct ch
{
char str[10];
};
void disp(ch d)
{
cout<<"\n"<<d.str<<"\n";
}
//delete part
cout<<"\nwant to delete??";
char c;
cin>>c;
if(c=='y')
{
char s[10];
cout<<"nter - ";
cin>>s;
file.seekg(0);
int found=0;
fstream temp("temp.dat",ios::in|ios::out|ios::app);
while(file.read((char *)&dta,sizeof(dta)))
{
if(strcmp(dta.str,s)==0)
{
found=1;
cout<<"deleted";
}
else
temp.write((char *)&dta,sizeof(dta));
}
if(!found)
cout<<"not found";
remove("new.dat");
rename("temp.dat","new.dat");
temp.close();
file.open("new.dat",ios::in|ios::out|ios::app);
}
EDIT: Looking over your code again, I see the problem is that you are using the ios::app although you have also passed ios::in.
ios::app -- All output operations are performed at the end of the file, appending
the content to the current content of the file. This flag can only be
used in streams open for output-only operations.
http://www.cplusplus.com/doc/tutorial/files/
Old Post:
Take a look at the following code example:
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
using namespace std;
const char g_szTestData[] = "This is some test da$$$$######ta and some more"
" tes$$$$######ting";
int main(int argc, char** argv)
{
fstream file("new.dat", ios::in|ios::out);
file << g_szTestData << flush;
cout << "Do you want to delete all $$$$######?";
if (cin.get() == 'y')
{
char szBuffer[10]; //< File read buffer
char szString[11] = "$$$$######"; //< 10 characters + '\0'
bool bFound = false;
fstream temp("temp.dat", ios::out);
file.seekg(0, file.beg);
while (file.read(szBuffer, sizeof(szBuffer)))
{
if (strncmp(szBuffer,szString,10) == 0) bFound = true;
else temp.write(szBuffer, sizeof(szBuffer));
}
temp.flush();
temp.close();
if (bFound)
{
file.close();
remove("new.dat");
rename("temp.dat", "new.dat");
file.open("new.dat",ios::in|ios::out);
}
else cout << "Pattern Not Found!" << endl;
}
/* Do something with the contents of file. */
// Lets clean up at the end
file.close();
return 0;
}
In this example, a file is created and the contents g_szTestData are added, you can verify this by opening the file (before pressing 'y').
The user is then asked if they would like to delete a string of 10 characters $$$$###### from the file. If the user wishes to proceed, a new file is opened temp.dat. The program gradually walks through the existing new.dat file (10 characters at a time). If the string the program reads from new.dat is not the target string, the string is written to the temp file.
If the target string is found, both files are closed, the old file is deleted and the new file is renamed to the name of the old file. The new file is then opened so the program can do additional work on its contents.
Instead of having a fixed 10 character string, it is possible to ask the user for the string they wish to remove using cin >> szString but the string would need to be 10 characters long.
Your code work as expected, it only display deleted because disp() isn't called anywhere.
#include <iostream>
#include <string.h>
#include <fstream>
#include <stdio.h>
using namespace std;
typedef struct {
char str[16];
} ch;
static void disp(ch d) {
cout<<d.str<<"\n";
}
int main(int argc, char **argv) {
fstream file;
ch dta;
file.open("new.dat",ios::in|ios::out|ios::trunc);
for (int i=0; i<3; i++) {
snprintf((char *)&dta.str, sizeof(dta.str)-1, "rec%d", i);
file.write((char *)&dta,sizeof(dta));
}
//delete part
{
char s[16] = "rec1";
file.seekg(0);
int found=0;
fstream temp("temp.dat",ios::out);
while(file.read((char *)&dta,sizeof(dta))) {
if(strcmp(dta.str, s)==0) {
found=1;
cout<<"deleted * ";
disp(dta);
} else {
temp.write((char *)&dta,sizeof(dta));
disp(dta);
}
}
if(!found)
cout<<"not found";
file.close();
remove("new.dat");
rename("temp.dat","new.dat");
temp.close();
}
}