Try to write char[] to a text file - c++

I trying to write a char[256] to a text file. Below is my current work:
fstream ofs;
ofs.open("c:\\myURL.txt");
ofs.write((char*)testDest,256);
ofs.close();
It still does not work.
here is the error:
error C2440: 'type cast' : cannot convert from '' to 'char *'
update:
so far, here is my progress attempt, the code can compile, but when running, my program suddenly terminated.
ofstream stream;
CBar *a;
switch(uMessage) {
case WM_PAINT:
return bar->OnPaint();
case WM_ERASEBKGND:
return 1;
case WM_LBUTTONDOWN: //wira
if (!bar->OnClick(wParam, lParam)) {
stream.open("C:\\myURL.txt");
stream << a->testDest << endl; // if I replace `a->testDest` with "testword" string, my prgrom does not terminated. Why?
return 0;
}
break;

Several things wrong or "not good" in your code:
You never check if the open fails.
You use clunky write functions.
You don't check if your write is succesful (not quite necessary if you're kind of sure it will work).
This will give you more info if something fails:
#include <fstream>
using std::ofstream;
#include <iostream>
using std::cout;
using std::endl;
int main()
{
ofstream stream;
char charArray[] = "Some stuff in a char array.";
stream.open("C:\\myurl.txt");
if( !stream )
cout << "Opening file failed" << endl;
// use operator<< for clarity
stream << testDest << endl;
// test if write was succesful - not *really* necessary
if( !stream )
cout << "Write failed" << endl;
return 0;
}
My guess is that opening the file failed because you lack proper permissions. The above program will tell you where what fails.
UPDATE: To answer your second question: you do this:
CBar* a;
Which creates a pointer but leaves it unitiallized. You then want to dereference it to access its testDest data member, which obviously leads to a crash. You need to initialize your pointer (or don't use a pointer here, I see no reason to):
// Either this
CBar* a = new CBar(/*some arguments, or none, depending on CBar definition*/);
//...
cout << a->testDest << endl;
// Or this (better here in my opinion)
CBar a; // OK if there is a default constructor (one with no arguments);
//...
cout << a.testDest << endl;
Please read any good tutorial on c++. These are mistakes you make either when you've not slept for three days or if you don't understand the basic concepts of the language.

You need to pass to fstream, in open(), the kind of operation you're expecting to do: input, output, or even both. You should try with:
ofs.open( "c:\\myURL.txt", ios::out | ios::text);
Anyway, it would be better to use ofstream instead of a generic fstream:
ofstream ofs;
ofs.open( "c:\\myURL.txt", ios::text );
ofs.write( (char*)testDest, 256 );
ofs.close();

You forget that if someone is trying to check if file exists, then if it doesn't create the file you have to use fstream for your object so is to not have 2 different objects for open and write

Related

fstream test program crashes for some reason

I have been playing around with the fstream class in C++ to see if I am able to write some data to a text file(.txt). According to what I know, If the program tries to write to a file that does not exist then it would automatically create that file, am I wrong? This program is very simple and does not give me any compiler errors which means it builds fine. However for some reason it crashes when I run it.
Here is my code:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
std::fstream* myFile;
int main()
{
int age = 15;
std::string myName = "Javier Martinez";
std::string friendsName = "David Lyn";
//Backslash is a special character, use double backslash or forward slash instead.
myFile->open("C:/Users/NIKE/Desktop/data.txt");
if (myFile->fail())
{
std::cerr << "File was unable to be opened.";
}
*myFile << age << "\n";
*myFile << myName << "\n";
*myFile << friendsName << "\n";
myFile->close();
std::cout << "File was successfully written to with the data";
return 0;
}
Any help is appreciated. Thank you in advance.
NOTE: I am using the GNU GCC compiler with Code::Blocks IDE
myFile is uninitialized. Check it.( Allocate memory) or simply use fstream.
Your problem stems from the line:
std::fstream* myFile;
You only declared a pointer to a stream object, which is initialized to nullptr by reason of it being in the global scope. The fact that you tried accessing a non-existent object (invalid) through it, you invoked what is known as Undefined Behavior.
You do not need to allocate stream objects on the heap, rather, do:
std::fstream myFile;
On a side Note: Check your program control flow:
if (!myFile)
{
std::cerr << "File was unable to be opened.";
}
else{
myFile << age << "\n";
myFile << myName << "\n";
myFile << friendsName << "\n";
}

c++ serialization of a structure

While compiling this simple code:
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
class Example
{
public:
char charo;
int into;
};
int main()
{
Example one,two;
one.charo = 'X'; one.into = 2;
//WRITING
ofstream file;
file.open("my.prx", ios_base::binary);
if(file.good()) file.write((char*)&one, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
file.close();
//READING
file.open("my.prx", ios_base::binary);
if(file.good())
file.read((char*)&two, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
file.close();
//PRINTING
cout << "CHAR: " << two.charo << endl;
cout << "INT: " << two.into << endl;
}
I get this error message:
g++ -o test1 main.c main.c: In function ‘int main()’: main.c:43:7:
error: ‘std::ofstream’ has no member named ‘read’
file.read((char*)&two, sizeof(Example));
How can I solve it?
My next step will be to make a more complicated object to save:
Class Memory{
t_monitor monitors[MAX_MONITORS];
t_status status[MAX_STATUS];
t_observer observers[MAX_OBSERVERS];
Var * first_var;
int tot_observers;
int tot_status;
int tot_monitors;
};
As you can see there is also a list...
ofstream is an output file stream. It's used for output, and can't "read".
Use fstream instead.
Use ifstream to read ostream is used for output.
You can do something like this
std::ifstream fileRead( "my.prx",std::ifstream::binary );
if(fileRead)
fileRead.read((char*)&two, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
fileRead.close();
An [ofstream][1] is output only. One readable way is to use the variables ofstream ofile and ifstream ifile. This way the usage is clear from the declaration and the name. If the code grows, this might be helpful.
Another way would be to use the dual-use fstream, but this can make certain operations ambiguous.
Of course, these days, you're probably better off using some sort of serialization library. First, preferring the one that your company or group already uses, and then, if that one is inadequate, picking a modern lib like Boost or, my fave, Cereal.

Why doesn't my function produce output

I'm doing a C++ assingment for a class and I haven't used C++ in a decade so this might be something I'm missing that is simple; however ,I can't seem to figure it out.
I have a class I defined with a function that is producing no output; it looks like it's not even running and I don't have a clue why. Could someone point out my problem to me?
Issue: cout from the function getwords of the class readwords doesn't display any results.
Here is my class:
class readwords {
private:
char c;
//string aword;
public:
void getwords(std::istream& file) {
cout << "I got here" << std::flush;
/*while(file.good()) {
cout << "I got here\n";
c = file.get();
if(isspace(c)) cout << "\n"; //continue;
if(isalnum(c)) {
cout << c; //aword.insert(aword.end(),c);
}
}
*/
}
};
Which is being called from my main:
#include <fstream>
#include <stdlib.h>
#include "lab1.h"
using namespace std;
readwords wordsinfile;
words wordslist;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) {
// Looks like we have no arguments and need do something about it
// Lets tell the user
cout << "Usage: " << argv[0] <<" <filename>\n";
} else {
// Yeah we have arguements so lets make sure the file exists and it is readable
ifstream ourfile(argv[1]);
if (!ourfile.is_open()) {
// Then we have a problem opening the file
// Lets tell the user and exit
cout << "Error: " << argv[0] << " could not open the file. Exiting\n";
exit (1);
}
// Do we have a ASCII file?
if (isasciifile(ourfile)) {
cout << "Error: " << argv[0] << " only can handle ASCII or non empty files. Exiting\n";
exit(1);
}
// Let ensure we are at the start of the file
ourfile.seekg (0, ios::beg);
// Now lets close it up
ourfile.close();
}
// Ok looks like we have past our tests
// Time to go to work on the file
ifstream ourfile2(argv[1]);
wordsinfile.getwords(ourfile2);
}
Thank you for any help you can provide.
Try to use a debugger. Most IDEs (NetBeans, Code::Blocks, etc) provide an interactive interface with gdb.
I just compiled and ran your code, but nothing wrong with the code itself,
except that I needed to include to use the 'cout' method.
"I got here" has been successfully displayed in my ubuntu machine.
What is your execution environment? You should check it first.
The problem appears to be redefining my own class. When actually coding the function I needed to use:
in readwords::countwords(std::istream& file) {
....
}
Once doing this output produced fine.

how to restore std::cin to keyboard after using pipe?

Problematic code:
#include <array>
#include <iostream>
#include <cstring>
int main(int argc, char *argv[])
{
using namespace std;
cout << "Read from file:" << endl;
while (!cin.eof())
{
array<char, 16> l_array;
cin.read(l_array.data(), l_array.size());
cout.write(l_array.data(), cin.gcount());
}
cout << endl;
cout << "Read from keyboard:" << endl;
cin.rdbuf(cout.rdbuf());
while (!cin.eof())
{
array<char, 64> l_array;
memset(l_array.data(), 0, l_array.size());
cin.read(l_array.data(), l_array.size());
cout << "===== DATA =====" << endl;
cout << l_array.data() << endl;
cout << "================" << endl;
}
}
This is how i run my program:
./application < file.txt
I can read data from pipe without problems but when i want to read it again it is still asociated with pipe. I have no idea how to switch it back. I have found 'rdbuf' function which can change it, but I have no idea how to use it.
I only found examples when you stard with keyboard switch to file and back to keyboard.
Like here: http://www.cplusplus.com/reference/iostream/ios/rdbuf/
But i don't have streambuf remembered so I can't do it like they did. I want to write program which can read most of data from file, and ask only when something is missing or just to ask user in runtime about permision or something. All inside console under linux.
#EDIT
Thank you for help, I post solution
class RedirectCinToConsole
{
protected:
std::ifstream m_console;
std::streambuf *m_oldCin;
bool m_success;
public:
RedirectCinToConsole() :
m_oldCin(0),
m_success(false)
{
m_console.open("/dev/tty");
if (m_console.is_open())
{
m_success = true;
m_oldCin = std::cin.rdbuf(m_console.rdbuf());
}
}
virtual ~RedirectCinToConsole()
{
if (m_oldCin)
{
std::cin.rdbuf(m_oldCin);
}
m_console.close();
}
operator bool () const { return m_success; }
};
int main()
{
RedirectCinToConsole l_redirect;
if (l_redirect)
{
std::string l_helloWorld;
std::cin >> l_helloWorld;
std::cin.ignore();
std::cout << l_helloWorld;
}
return 0;
}
It occurs to me that, regardless of the proposed solutions, the easiest
solution (and probably the best) would be to do things the opposite:
don't redirect the input, but pass the filename to the program, and let
it open an std::ifstream to read it, keeping std::cin free for
interactive input.
Ben Voigt has suggested the standard Unix solution, but on thinking
about it, it seems the above is more natural; it is certainly easier and
more portable.
Perhaps you should use fstream to create your own stream and either ask for a file name or take the file name as a command-line parameter. This will leave cin available for other input operations.
Try opening /dev/tty. This will be your process's associated console, if there is any. If your process was started from a daemon, it could fail.

Why does ofstream sometimes create files but can't write to them?

I'm trying to use the ofstream class to write some stuff to a file, but all that happens is that the file gets created, and then nothing. I have some simply code here:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
ofstream file;
file.open("test.txt");
if (!file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
for (int i = 0; i < 10; i++) {
file << i << "\t" << time(NULL) << endl;
}
file.flush();
file.close();
return 0;
}
When I create a console application, everything works fine, so I'm afraid this code is not completely representative. However, I am using code like this in a much larger project that - to be honest - I don't fully understand (Neurostim). I'm supposed to write some class that is compiled to a dll which can be loaded by Neurostim.
When the code is run, "test.txt" is created and then "No error!" is printed, as this is apparently the output from strerror. Obviously this is wrong however. The application runs perfectly otherwise, and is not phased by the fact that I'm trying to write to a corrupted stream. It just doesn't do it. It seems to me like there is no problem with permissions, because the file is in fact created.
Does anyone have any ideas what kind of things might cause this odd behavior? (I'm on WinXP Pro SP3 and use Visual C++ 2008 Express Edition)
Thanks!
Just a thought :- in your real code are you re-using your stream object?
If so, you need to ensure that you call clear() on the stream before re-using the object otherwise, if there was a previous error state, it won't work. As I recall, not calling clear() on such a stream would result in an empty file that couldn't be written to, as you describe in your question.
ofstream file;
file.open("test.txt");
Just a nit: you can combine that into a single line. ofstream file("test.txt");
if (file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
Your test is backwards. If file is true, it's open and ready for writing.
Also, I wouldn't count on strerror() working correctly on Windows. Most Windows APIs don't use errno to signal errors. If your failure is happening outside the C/C++ run-time library, this may not tell you anything interesting.
UPDATE Thinking more about this, failing to open a file via fstreams is not guaranteed to set errno. It's possible that errno ends up set on some platforms (espeically if those platforms implement fstream operations with FILE* or file descriptors, or some other library that sets errno) but that is not guaranteed. The official way to check for failure is via exceptions, std::io_state or helper methods on std::fstream (like fail or bad). Unfortunately you can't get as much information out of std::streams as you can from errno.
You've got the if statement wrong. operator void* returns NULL (a.k.a. false) if the file is not writable. It returns non-zero (a.k.a. true) if the file is writeable. So you want:
if (!file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
Or:
if (!file.good()) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}