Reading in a data file

Started by
2 comments, last by snk_kid 18 years, 10 months ago
quick question ... if you are gonna load a file (text or binary ) what is the best method for that... I have not looked much in to it... but the only one i have used is fstream.... any others? (i am using c or c++******* ;P q;
Advertisement
I like to use the IO stream methods in the CRT. (fopen, fread, etc) but I'm old-school. One upside of using them is they're pretty standard; PHP has file IO methods that mirror the ones in the CRT.


MSDN reference on IO Stream methods
or use std::fstream!
its just like cin(and cout),because it is the same types!
lets say we have a file like this:
hellomynameisbob

#include <fstream>#include <iostream>int main(int argc,char** argv){fstream file("somefile.txt",std::in);//open file for input.char lines[5][50];//the numbers in the file will be stored in here.for(int i=0;!file.eof();i++)//read all numbers until the end of the file.{file.getline(lines,50);}cout<<lines[0]<<"<<lines[1]<<" "<<lines[2]<<" "<<lines[3]<<" "<<lines[4];}

will output "hello my name is bob".
I program in my sleep,but when I sleep I use the partition in my head that doesnt have g++ or the .net library, so im kinda screwed.
Quote:Original post by supercoder74
or use std::fstream!
its just like cin(and cout),because it is the same types!


Not quite, how-ever they are sub-types of basic_i/o(io)stream so they are interchangeable where-ever there is a reference to those super types.

Quote:Original post by supercoder74
lets say we have a file like this:
*** Source Snippet Removed ***
*** Source Snippet Removed ***
will output "hello my name is bob".


or more simply:

#include <algorithm>  // copy#include <iterator>   // istream_iterator, ostream_iterator#include <vector>#include <string>#include <fstream>#include <iostream>int main() {   typedef std::vector<std::string> vec_of_strs;   typedef std::istream_iterator<std::string> iss_itr;   typedef std::ostream_iterator<std::string> oss_itr;   std::ifstream ifs("temp.txt");   vec_of_strs v((iss_itr(ifs)), iss_itr());   std::copy(v.begin(), v.end(), oss_itr(std::cout, " "));}


We could make it less verbose with some boost lambda magic but thats another story...

This topic is closed to new replies.

Advertisement