This snippet is part of a big program. The problem I am facing is that when I write a string to the file using "write" member function, it do not show last character of string:
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
fstream file1("/users/xxxxxxx/desktop/file1.txt", ios::out);
string data;
cout << "Enter string: " << endl;
getline(cin, data);
file1.write(reinterpret_cast<char*>(&data), data.size());
//file1 << data;
file1.close();
return 0;
}
For Example: If Input String: "Hello World".
On File it will show: "Hello Worl",
But it does work fine if I input string using "file1 << data". Please help me in this
file1.write(reinterpret_cast<char*>(&data), data.size());
Don't do this, you are writing the string object itself to the file. if you really want to use write you have to get a pointer to the first char that the string holds, like this:
file1.write(data.data(), data.size());
Just use the << operator.
Why would you cast the address of a string into a char*? This isn't a meaningful conversion--you are casting a std::basic_string<char>* to char*. I suspect you want to treat string as char* since write accepts const char* as parameter. You can access the character sequence stored in your data by doing data.c_str().
Related
1I am currently working on a project of creating my own game in OpenGL. My problem is right now, that if I read a file, that my function reading that file results in a SIGABRT, because of something inside the std::ifstream deconstructor (more specifically in "std::basic_ifstream<char, std::char_traits<char> >::~basic_ifstream()"). This function previously worked for me, but suddenly stopped working.
My Goal is simple: A reliable implementation for reading a file to a char*. Multi threading is currently not my concern.
Here is my implementation of the file reading function.
It takes in a path, and should write the content of the file at that path into the out parameter.
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <cassert>
#include "Utility.h"
char * Utility::readFile(const char* path,char*& out){
#ifndef NDEBUG
std::cout<<"Getting file: "<<path<<"\n";
#endif
// Open the file, but freak out if not valid.
std::ifstream file=std::ifstream(path);
assert(file.good());
if(!file.good())
{
throw std::runtime_error((std::string)"Couldn't open file for loading: "+path);
}
// Read the file contents into a char buffer.
std::stringstream buffer;buffer << file.rdbuf();
std::string fileContentsStr = buffer.str();
out = new char[fileContentsStr.size()];
strcpy(out,fileContentsStr.c_str());
return out;
}
My code is located at C0D3-M4513R/OpenGlGame.
I already tried a minimal example, which is working and using the same compile flags (except linker flags). test.txt and test1.txt just contain some rubbish text generated by randomly hacking on my keyboard.
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
//This Function is the same as the one above!!!
char *readFile(const char *path, char *&out) {
#ifndef NDEBUG
std::cout << "Getting file: " << path << "\n";
#endif
// Open the file, but freak out if not valid.
std::ifstream file = std::ifstream(path);
assert(file.good());
if (!file.good()) {
throw std::runtime_error((std::string) "Couldn't open file for loading: " + path);
}
// Read the file contents into a char buffer.
std::stringstream buffer;
buffer << file.rdbuf();
//convert the stringstream to a string
std::string fileContentsStr = buffer.str();
//copy the contents of the string to a char array
out = new char[fileContentsStr.size()];
strcpy(out, fileContentsStr.c_str());
//return char array address (which should be the same as the start?)
return out;
}
int main() {
//The programm started!
std::cout << "Hello, World!" << std::endl;
//Define a space for the contents of the file to live
char *out;
//Read the contents of a file
out = readFile("test.txt", out);
//Print contents of the file
std::cout << out << std::endl;
char *out1;
//Read the contents of a file
out1 = readFile("test1.txt", out1);
//Print contents of the file
std::cout << out1 << std::endl;
return 0;
}
strcpy:
Copies the character string pointed to by src, including the null terminator, to the character array whose first element is pointed to by dest.
The behavior is undefined if the dest array is not large enough. The behavior is undefined if the strings overlap.
c_str:
Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.
out = new char[fileContentsStr.size()];
strcpy(out,fileContentsStr.c_str());
You need to be careful when mixing std::string with c-strings, because a std::string is not null-terminated and does not count the nullterminator for its size. However, c_str does return a pointer to a null-terminated character array.
You are asking strcpy to write fileContentsStr.size()+1 (size + null terminator) into a char array with only fileContentsStr.size() elements.
PS: As mentioned in a comment, you should consider to return a std::string instead. You are using a raw owning pointer which is error prone and should be avoided. Either use a smart-pointer or let a std::string manage the char-array (thats what its made for actually ;).
In this function what I have to do is pass the strings from txt file in char and do some operations. My only problem is on pass file from txt to char. how i should fix it?
char* foo(string& input){
stringstream ss;
ss<<input;
char *elements=new char[32];
elements[32]='\0';
ss>>elements; //next part code not written because useless
This is how you can store data in a char array from a file:
Source File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("Input File.txt");
char Array[50] = { ' ' };
inFile.get(Array, 50);
cout << "Output : " << Array << endl;
inFile.close();
}
Text File
Enter Text Here
If you want i can make a dynamic array for you which will have the exact size as the string (Data you input) from file or use vectors because they can easily be expanded and shortened in late binding(means: during program execution).
I need to convert a std::string to a const char*.
To do so, I used the c_str() method on the string, as in the following code :
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string testStr;
cin >> testStr;
const char* testStrConst = testStr.c_str();
cout << testStrConst << endl;
return 0;
}
If I type "Hey hello" in the terminal, when this code is running, the output is only "Hey".
Why is the second word ignored?
Because it was never a part of the std::string in the first place.
The >> operator reads only a single, whitespace delimited word.
Use std::getline() instead of >> to read the entire line of text entered on standard input.
string testStr;
getline(cin, testStr);
I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)
i have a little problem on writing the string into a file,
How can i write the string into the file and able to view it as ascii text?
because i am able to do that when i set the default value for str but not when i enter a str data
Thanks.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
fstream out("G://Test.txt");
if(!out) {
cout << "Cannot open output file.\n";
return 1;
}
char str[200];
cout << "Enter Customers data seperate by tab\n";
cin >> str;
cin.ignore();
out.write(str, strlen(str));
out.seekp(0 ,ios::end);
out.close();
return 0;
}
Please use std::string:
#include <string>
std::string str;
std::getline(cin, str);
cout << str;
I'm not sure what the exact problem in your case was, but >> only reads up to the first separator (which is whitespace); getline will read the entire line.
Just note that >> operator will read 1 word.
std::string word;
std::cin >> word; // reads one space seporated word.
// Ignores any initial space. Then read
// into 'word' all character upto (but not including)
// the first space character (the space is gone.
// Note. Space => White Space (' ', '\t', '\v' etc...)
You're working at the wrong level of abstraction. Also, there is no need to seekp to the end of the file before closing the file.
You want to read a string and write a string. As Pavel Minaev has said, this is directly supported via std::string and std::fstream:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream out("G:\\Test.txt");
if(!out) {
std::cout << "Cannot open output file.\n";
return 1;
}
std::cout << "Enter Customer's data seperated by tab\n";
std::string buffer;
std::getline(std::cin, buffer);
out << buffer;
return 0;
}
If you want to write C, use C. Otherwise, take advantage of the language you're using.
I can't believe no one found the problem. The problem was that you were using strlen on a string that wasn't terminated with a null character. strlen will keep iterating until it finds a zero-byte, and an incorrect string length might be returned (or the program might crash - it's Undefined Behavior, who knows?).
The answer is to zero-initialize your string:
char str[200] = {0};
Supplying your own string as the value of str works because those in-memory strings are null-terminated.