how do i read data from a file?

This is a discussion on how do i read data from a file? within the C++ Programming forums, part of the General Programming Boards category; hey say i made a file called data.dat and say i put this into the file 7 8 9 20 ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    255

    how do i read data from a file?

    hey say i made a file called data.dat and say i put this into the file
    7
    8
    9
    20

    how would i read data from that file i think it has to do with ifstream but i didnt quite understand it the way my book explained it
    if anyone knows id appreciate it if they can tell me
    hooch

  2. #2
    Hamster without a wheel iain's Avatar
    Join Date
    Aug 2001
    Posts
    1,385
    if you are going to set up the datafile like that you could read it as

    use fopen to open it with ios set to in

    datafile.open("datafile.dat", ios::in)
    then set up the ints that will hold the variables, say int1, int etc

    then read then im

    datafile<<int1;
    datafile<<int2;

    as they are on seperate lines, they are seperated so you can read them in like thsi

    hth
    Monday - what a way to spend a seventh of your life

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Code:
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        ifstream InputFile("file.txt");
        int iVal1, iVal2, iVal3, iVal4;
    
        InputFile >> iVal1 >> iVal2 >> iVal3 >> iVal4;
        cout << iVal1 << ' ' << iVal2 << ' ' << iVal3 << ' ' << iVal4 << endl;
    
        return 0;
    }
    Assuming you named your file "file.txt".
    "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

  4. #4
    Unregistered
    Guest
    You should be aware that using a FILE * to handle files is also possible, and some people prefer it.

    Furthermore, the syntax provided is just the simplist syntax possible. In particular it is the syntax for use when the file you wish to read is in the same file (I prefer to say directory or subdirectory) as your compiler. If that is not the case, then the full file path, with appropriate C++ syntax, must be used. As long as you keep it simple and follow the rules, the syntax as used in the previous posts should work fine.

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ok i ran that code but all that does is create a file and output in dos sum numbers how would i im liek still confused on what the purpose of ifstream is i understand ofstream cuz i could do the same thing by jus using cin to get input and then going object>>varaible;
    but how does ifstreamhelp me at all im still kinda confused on that
    hooch

  6. #6
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    There is a FAQ on file IO. Use it...


    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
    
       ofstream out;
       ifstream in;
       char ch;
    
       out.open("file.dat");
       if (out.fail()) 
       { 
         cout << "error opening ouput file" << endl;
         return 1;
       }
    
       out << "1235\n6789\n\n10";
       out.put('\n');
    
       out.close();
    
       in.open("file.dat");
       if (in.fail())
       {
          cout << "error opening input file" << endl;
          return 1;
       }
    
       while (!in.eof())
       {
          in.get(ch);
          cout << ch;
       }
    
       in.close();
    
    return 0;
    } // end main
    Last edited by Betazep; 01-31-2002 at 11:29 AM.
    Blue

  7. #7
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    >>>In particular it is the syntax for use when the file you wish to read is in the same file (I prefer to say directory or subdirectory) as your compiler.


    You probably meant this... but just to keep from giving people wrong information, if you do not use a path statement... the file needs to located in the same directory as the executable. The compiler directory is irrelevant, and you shouldn't compile projects in the same directory as your compiler binary anyway. Utilize workspaces...
    Blue

  8. #8
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    hmm well ima guess that cin.put('\n') inputs the in>>"blablah"; into the file?until the '\n' is met? and i dunt kno .eof() really at all to well and y did u have a return 1;// i only use return to return a function or return 0 and um i also kno of cin.get();
    but i dunt kno of a output.get()????????????????
    hooch

  9. #9
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    sorry...

    that should be

    out.put('\n');


    input_buffer.put(char) places a single character and increments the current cursor pointer. Much like output_buffer.get(char) takes one character (as seen in the output/read application).

    So when you have an input file open and you do this

    for (int i = 0; i < 10 ; i++)
    {
    out.put('C');
    }

    You would get

    CCCCCCCCCC

    in your input file (assuming out was type ofstream and the file was open) Simple... huh?

    if you did this

    char ch;
    ofstream out;

    out.open("file.txt");

    while (ch != '#')
    {
    cin >> ch;
    out.put(ch);
    }

    out.close();

    you would be able to write into a text file by typing at the console. Every letter you type goes into the text file until a # is encountered which will also be put in the text file, but will stop the loop.

    .eof() is end_of_file

    so while not end of file, get a character and write it to the screen. So your entire file will be written to the screen.

    Any more questions?
    Last edited by Betazep; 01-31-2002 at 11:23 AM.
    Blue

  10. #10
    Registered User WebSnozz's Avatar
    Join Date
    Oct 2001
    Posts
    102
    Someone mentioned using a FILE *, I don't understand that but sounds interesting, could you post some syntax of putting a short something in and then reading it back out of a file using that please...
    WebSnozz-
    Cats have no butt cheeks.
    If one farted, then it would make a flute noise.

  11. #11
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Using FILE* is the good old C way of doing things, since this is the C++ board and not the C board, my example above used C++ file streams. If you want to do it the C way, this is a sample of what you can do:
    Code:
    #include <stdio.h>
    int main()
    {
        FILE* Input;
        FILE* Output;
        int iValue;
    
        // Open file for writing.
    
        Output = fopen("data.txt","w");
        if( Output != NULL )
        {
            fprintf( Output, "%d", 10 );
            fclose( Output );
        }
    
        // Open file for reading.
    
        Input = fopen("data.txt","r");
        if( Input != NULL )
        {
            fscanf( Input, "%d", &iValue );
            fclose( Input );
            printf( "Read the value %d from the file.\n", iValue );
        }
    
        return 0;
    
    }
    The file "data.txt" will be created by the program, overwritten if it already exists. After the program runs, if I've done everything correctly here and not made any mistakes, the file should contain "10".
    "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

  12. #12
    Unregistered
    Guest
    I appreciate Betazep's resopnse pointing the importance of using the full path name if the file is not located in the same directory as the programs executeable file, as opposed to the directory of the compilers file, as I had posted. Thankyou.

    In addition, it's nice to see that even people who have posted >700 times can slip up as easy as the rest of us:

    "you don't use ifstream to read from a file, you use ofstream"

    That's wrong according my textbook. If you are going to read information from a file to a program you should not use an ofstream; you should use an ifstream (or an fstream with ios::in). ofstream (or fstream with ios:ut) is for writing information to a file from your program.

    Taking the brave step of disagreeing with someone more experienced than myself, the above error is then propogated in the following snippet where it makes no sense to overwrite user input stored in ch with input from the file:

    char ch;
    ifstream in;

    in.open("file.txt");

    while (ch != '#')
    {
    cin >> ch;
    in.put(ch);
    }

    I suspect Betazep was attempting to write user input to a file character by character until a terminating # occurs, rather than overwrite use input, but, without comments, you never know for sure.

    Oh, well. Live and let live...and respectfully correct each others' errors.

  13. #13
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    >>>In addition, it's nice to see that even people who have posted >700 times can slip up as easy as the rest of us:

    "you don't use ifstream to read from a file, you use ofstream" <<<


    LOL... that is wrong according to every text book. Nice catch. Hard to write code at work sometimes. No compiler. No books. All off of memory.

    I made the necessary changes so as to not further confuse people.

    Thanks.
    Blue

  14. #14
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    hmmm so ofstream like i thought is used to read data from a file and input data to a file? so then ifstream is used for????? u guys made it sound like pretty much the same thing sorry if im being kinda slow with this heh im like that sumtimes
    hooch

  15. #15
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,136
    From what I understand, use ofstream to output into the file. Use ifstream to read a file.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. Read data from file - C program ?
    By Pawan Sangal in forum C Programming
    Replies: 2
    Last Post: 08-22-2008, 04:28 AM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21