How to import and export a text file in C++

Started by
13 comments, last by ShadowBranch 17 years, 9 months ago
Quote:Original post by ShadowBranch
just to add my bit to this. This is th best algorithm I use for reading from files and then later writing to files. It's along the same lines and uses simple items to be converted to whatever you want later.

#include <iostream>
using namespace std;
#include <fstream>
#include <cstring>
#include <string>

bool ReadFrom(char File[255]){
fstream theFile;
theFile.open(File, ios::in);
if(theFile.is_open() == 0){
cout << "ERROR: Failed to open the file! Check the file name!\n";
return(false);
}
while(theFile.good()){
string buffer;
getline(theFile, buffer);
}
return(true);
}

bool WriteTo(char File[255]){
fstream theFile;
theFile.open(File, ios::out);
// to write a basic::string or others, use this
theFile << [your-stuff-here];
// to write a character, such as a linefeed i would suggest this
theFile.write("\n", 2);
// the write function has two params, info to write, length of info
}


Hello ShadowBranch,

Just some comments.

1) Your buffer is defined locally. You need to define your function in such a way as to return it before it is destroyed at end-of-scope.

2) Your WriteTo function has no return statement.



Regards,
Joshua
Advertisement
I learnt file I/O from this GameDev article, maybe it'll help you out:
Click clik
Oops, got log out... here's the link again:

I learnt file I/O from this GameDev article, maybe it'll help you out:
Click clik
Quote:Original post by ShadowBranch
just to add my bit to this. This is th best algorithm I use for reading from files and then later writing to files.


- You don't use anything from <cstring> in the illustrated program (thank goodness), so don't include it. (Technically, I don't use iostream below, but it's almost certain to be used in a full program, whereas you would only need to include cstring if you were using stuff like strlen() etc., which you really shouldn't be using in normal circumstances.)
- Declaring a parameter as 'char File[255]' is rather silly: it doesn't actually limit the input, and there is no reason to do so anyway. It's more useful to accept a string by const reference and convert it with .c_str(); a passed-in string literal then gets converted back and forth, but it will still work - whereas you can't pass a std::string to a function expecting const char*.
- Don't use .open() on an fstream that you just declared. Instead, use the constructor that takes the .open() arguments. Remember, initialization != assignment, and you should initialize variables to their initial value when you know what that is.
- is_open() returns a bool. You should treat bools as if they were, you know, boolean: don't compare them to literals in order to answer 'if' conditions, because they already are the type that fundamentally represents the answer to a yes-or-no question.
- Use ifstream and ofstream to be specific; then ios::in and ios::out respectively are implied.
- Don't put parentheses around the things you're going to return; 'return' is not a function but a keyword.
- It might be a good idea to actually return the stuff that is read from a file, so that something can be done with it. Doing all the processing inside ReadFile() would be horrendously poor code organization.
- Don't handle errors by printing a local message and then returning a status value. If you're determined to indicate the error with a status value, you should let the calling code print the message as part of its error handling. Here, however, I would recommend either throwing an exception, or just returning an empty data set.
- Use the 'while (reading operation)' idiom for looping over input files.
- There's no reason to invoke .write() to output characters, especially if all the other I/O is using formatted I/O via the operator<<. This operator is overloaded to handle chars, including character literals (such as '\n' - notice *single* quotes) in the way you would expect it to. Note that writing 2 bytes for "\n" would also write the null terminator into the file, which is often not what you want (although probably benign).

#include <iostream>#include <fstream>#include <string>#include <vector>#include <exception>using namespace std;vector<string> ReadFile(const string& name){  ifstream theFile(name.c_str());  if (!theFile.is_open()) {    throw runtime_error("File not found");  }  vector<string> result;  string line;  while (getline(theFile, line)) {    result.push_back(line);  }  return result;}


Just as a note, That was just a chunk from my program that I pulled and modified very quickly. It wasn't supposed to be 100% accurate as it is originally from a class I created for file i/o. I assume that if a programmer is asking about File I/O, they have enough knowledge to correctly implement the bit. Again, that's from my class, so overall, the code is correct when in the class, not what I showed, hopefully a basic c++ programmer with even 6 months of experience could get that code working easily.

Just to make everyone happy, here is the proper code to use! This still utilizes the fstream only command as that will allow you to create a single file for read and write. but you can change it to use ifstream for in and ofstream for out.


#include <iostream>
using namespace std;
#include <fstream>
#include <string>

class CFileIO{
public:
bool ReadFrom(string File);
bool WriteTo(string File);
void WriteToBuffer(string Info);

protected:
string buffer;
};

void CFileIO::WriteToBuffer(string Info){
buffer.clear();
buffer.assign(Info);
}

bool CFileIO::ReadFrom(string File){
fstream theFile;
theFile.open(File, ios::in);
if(!theFile.is_open()){
while(theFile.good()){
getline(theFile, buffer);
// call a processing command here
}
return(true);
}else{
return(false);
}

bool CFileIO::WriteTo(string File){
fstream theFile;
theFile.open(File, ios::out);
if(theFile.is_open()){
theFile << [your-stuff-here];
return(true);
}else{
return(false);
}
}


BTW, I use return() as it is the way I've always returned data. It allows me to see exactly what is returned. I was taught to not use () but I've found it is easier for me when I use them. Just a programming preference, We are not look for everyone to code the exact same way. That is why the original code is there. Not as an exact copy and paste but for someone to learn. How else if a person to learn how to code if people hand them full code sets? and say here just copy this to your program and call the function. I had to get a book called the C++ primer, then read it for file io. Next I got on websites and read more. Found more ways of doing, next I hit the IRC chat rooms and found more ways. Once I had this list, I found the way I liked the best. This is what this guys should do. Don't hand people full code and say it works here. They have to learn. They will take a basic function and in a year rewrite it as they have learned more, then maybe later again.

Not everyone wants to have code that they don't know how it works. Some of us like code that will work but only after we take a little bit to see how it works. I do this, hopefully everyone else does, if they don't we have some bad programmers out there.

[Edited by - ShadowBranch on July 28, 2006 12:20:37 PM]

This topic is closed to new replies.

Advertisement