Advice on file io in c++

willmac

Registered
I was wondering if someone could help me out? I am a programming newby and wrote this small app. I would like to add some file io code to do the following - on launch invoke the user to name an output file and then for the app to write the output to that file as well as the terminal window. The app would then close the output file when finished.

I posted this query on a c++ forum and got flamed - I think they thought that the question was a bit simple :(. Anyways here is my wee app - attached txt file).

Any help would be great.

will
 

Attachments

  • main.txt
    5 KB · Views: 13
You can use IOStreams.
#include iostream (put angle brackets around iostream in your code)

Then you can create an output stream:
std::eek:fstream file;
file.open("name_of_file");

write to the file:
file << "text to write" << std::endl;

you use the file stream the same way as you would use cout.
;)
 
A more c'esque way would be to:

Code:
#include "stdio.h" // should use brackets here, but quotes will work

// we will overwrite the existing file here
// use "a" instead of "w" to append instead
outputFile = fopen(outputFileName,"w");
// error checking here
if (outputFile == 0) {
   doSomeErrorRelatedStuff();
   exit(1);
   }

// here you output to the file
fprintf(outputFile,"%s\n",outputString);

// after you are all done, close the file (forget to do this and 
// your file may be incomplete due to file buffering).
fclose(outputFile);

Generally more error checking could be done (of course), but this will show you the gist.

If you want to get fancy, you can write a function that mimics printf/fprintf and writes to both console and file if appropriate, this way your "outer" logic just calls a single function and doesn't worry about how many different places to output a file to.

e.g.

Code:
int writeText(char *formatString, ...)
{
...
if (outputToConsole)
   printf( ....... );
if (outputToFile)
   fprintf( ....... );
...
}

main()
{
...
writeText("> %s\n",stringToWrite);
...
}

Of course there are many other ways as well, which one is most appropriate just depends on your app. But this should be enough to get you started and to maybe branch out a bit as well.
 
willmac

Sorry you were flamed. I hate internet flamers. Most of them are ignorant jack-a$$es who don't have the balls to criticize even a slug in person.

Sorry about the rant but I really hate it when somebody asks a question and gets treated poorly. No question is too simple. All programmers had or still have those questions.

Technically, I have nothing to add. The others answered your question well.
 
Back
Top