Thread: Reading From Files

  1. #1
    Fallen AndyBomstad's Avatar
    Join Date
    Jan 2005
    Posts
    52

    Reading From Files

    ok i know how to use the Fstream header to use ofstream and write to text files but i kinda need some help on reversing it, can you guys give me the rundown on how to read and import stuff from a file to my program any help would kick ass, thanks guys

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by AndyBomstad
    ass
    Does the profanity filter catch anything at all, or just random words?

    You would use ifstream in just about the opposite manner that you use ofstream. Pseudocode:
    Code:
    load()
    {
       ifstream infile;
       infile >> all your data
    }
    
    save()
    {
       ofstream outfile;
       outfile << all your data
    }
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  3. #3
    Fallen AndyBomstad's Avatar
    Join Date
    Jan 2005
    Posts
    52
    yeah i was thinkin it was just reversed like

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    void main()
    {
         ifstream filein;
         filein.open("c:\test.txt");
         filein << "text";
    but im not sure, like if the time i output it to the file and only wrote "TEXT" whould i do just what my program says "filein << "text";" or would i want to bring in Everything on that file?

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Watch out, I'm about to go nuts...

    Code:
    #include <fstream>
    #include <iostream>
    #include <iterator>
    #include <algorithm>
    #include <list>
    #include <vector>
    #include <cstdlib>
    #include <ctime>
    
    int main()
    {
        // Seed random number generator
        srand((unsigned)time(NULL));
    
        // Generate 10 random numbers, stuff into a vector container.
        std::vector<int> intVect;
        std::generate_n(std::back_inserter(intVect),10, rand);
    
        // Open output file and write the 10 random numbers stored in vector container to the file
        std::ofstream output("file.txt");
        std::copy(intVect.begin(),intVect.end(),
                  std::ostream_iterator<int>(output," "));
    
        // Close the output file so we can open it below
        output.close();
    
        // Open an input file and create a list container
        std::ifstream input("file.txt");
        std::list<int> intList;
    
        // Read random ints from file into list container
        std::copy(std::istream_iterator<int>(input),std::istream_iterator<int>(),
                  std::back_inserter(intList));
    
        // Output contents of vector to cout
        std::cout << "Vector: ";
        std::copy(intVect.begin(),intVect.end(),
                  std::ostream_iterator<int>(std::cout," "));
    
        // Output contents of list to cout
        std::cout << "\nList  : ";
        std::copy(intList.begin(),intList.end(),
                  std::ostream_iterator<int>(std::cout," "));
        std::cout << std::endl;
    
    }
    Sample output:
    Code:
    Vector: 1646 15613 7177 3498 1960 31613 20293 2054 15271 22660 
    List  : 1646 15613 7177 3498 1960 31613 20293 2054 15271 22660
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    1) You want to test to make sure the file was opened properly before reading, so you can do something like this:
    Code:
    if(!inFile)
    {
        cout<<"Failed to open file."<<endl;
        return 1;
    }
    2) You need to decide how much data you want to read in from the file: one character, the first word, or the whole line. If you want to read in the first word, read the data into a variable using the >> operator just like you would with cin, except substitute in your ifstream object's name:

    string s;
    inFile>>s;
    cout<<s<<endl;



    If you want to read in other amounts of data, you can use the get() or getline() functions.
    Last edited by 7stud; 02-14-2005 at 04:56 PM.

  6. #6
    Fallen AndyBomstad's Avatar
    Join Date
    Jan 2005
    Posts
    52
    alright thanks guys, i got all that working with the putting it into the string and all, but like he mentioned using the getline() how would i go about using that?

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    string s;
    getline(inFile, s); //reads in the whole line
    cout<<s<<endl;


    char ch;
    inFile.get(ch); //reads in one character
    cout<<ch<<endl;


    char char_array[10];
    inFile.getline(char_array, 10);
    //reads in 9 chars(C++ tacks on a '\0' taking up the last spot)
    //or until the end of the line

    cout<<char_array<<endl;
    Last edited by 7stud; 02-14-2005 at 05:14 PM.

  8. #8
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    AAAAAAAAAAAHHHHHHHHHHHHHH no one commented on him using void main()
    My computer is awesome.

  9. #9
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    Quote Originally Posted by 7stud
    string s;
    getline(inFile, s); //reads in the whole line
    cout<<s<<endl;


    char ch;
    inFile.get(ch); //reads in one character
    cout<<ch<<endl;


    char char_array[10];
    inFile.getline(char_array, 10);
    //reads in 9 chars(C++ tacks on a '\0' taking up the last spot)
    //or until the end of the line

    cout<<char_array<<endl;
    ive been trying to do the same thing as well, 7stud i tryed your code and it works in part, from what i can understand the error occurs when the program encounters '\0' and by doing so it skips 1 line and goes to another.

    for example. if i have an array
    Code:
    7
    4
    3
    2
    6
    5
    by using what you posted the array is displayed as

    Code:
    Enter filename->        array1.txt
    7
    
    3
    
    6
    any soultions? as you can see it skips every other number in the array.
    When no one helps you out. Call google();

  10. #10
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Posting your code would help, but until then here is an example program that prompts the user to enter a file name and then reads the file into a vector and subsequently prints out the vector.
    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    int loadFile(vector<int>*, const char*);
    
    int main() {
    
        vector<int> vFile; //create vector to hold file information
        vector<int>::iterator iFile; // create iterator to move through vector
        char fileName[10];
    
        cout << "Enter the name of the file: ";
        cin.getline(fileName, 10);
    
        if((loadFile(&vFile, fileName)) == 1) { //load our file into the vector and check for an error
            cout << "Error Loading File" << endl;
            cin.get();
            return 1;
        }
    
    
        cout << "Printing from the file:" << endl;
        
        
        for(iFile = vFile.begin(); iFile < vFile.end(); iFile++) { //move through the vector
            cout << *iFile << endl;
        }
        
        cin.get();
        return 0;
    }
    int loadFile(vector<int>* my_vector, const char * szfileName) {
    
        ifstream myFile;
        int myNumber = 0;
    
        myFile.open(szfileName, std::ios::in);//Load the file
    
        if(myFile == NULL) //check for error
            return 1;
    
        while(!((myFile >> myNumber)==NULL)) { //check for EOF
            my_vector->push_back(myNumber); // load contents of file into vector
        }
    
        myFile.close();
        return 0;
    }
    In my file I have:
    10
    20
    34
    23
    12
    34
    5
    85
    43
    10
    And my output is:
    Last edited by andyhunter; 02-14-2005 at 06:07 PM.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  11. #11
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Quote Originally Posted by InvariantLoop
    ive been trying to do the same thing as well, 7stud i tryed your code and it works in part, from what i can understand the error occurs when the program encounters '\0' and by doing so it skips 1 line and goes to another.
    Unfortunately, I have no idea what you are talking about. The program encounters '\0'?? Where?? When??? How?? You have to be more specific. C++ is a very strongly typed and tightly structured language, and the specifics are very important, so talking in vague generalities as if you were having a conversation over a beer with a friend doesn't cut the mustard--it's all in the details.
    ...for example. if i have an array
    Code:
    7
    4
    3
    2
    6
    5
    An array?? Where?? An array is a C++ construct. Here is a C++ array:

    char str[20];

    In C++, you say str is an array. Where is your array?

    ...by using what you posted the array is displayed as
    Code:
    Enter filename->        array1.txt
    7
    
    3
    
    6
    What array??

    any soultions? as you can see it skips every other number in the array.
    This thread is about file input and ouput, and you are talking about arrays, so I think you might be mixed up
    Last edited by 7stud; 02-14-2005 at 09:30 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading User Defined Files
    By Necrofear in forum C++ Programming
    Replies: 17
    Last Post: 06-30-2006, 12:55 AM
  2. Linking header files, Source files and main program(Accel. C++)
    By Daniel Primed in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:46 AM
  3. reading files
    By hiya in forum C++ Programming
    Replies: 7
    Last Post: 05-21-2005, 11:40 AM
  4. A little help reading from files...
    By Invincible in forum C++ Programming
    Replies: 4
    Last Post: 04-03-2002, 10:43 AM
  5. Need Advice in reading files
    By jon in forum C Programming
    Replies: 4
    Last Post: 10-07-2001, 07:27 AM